meuget 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
meu.py ADDED
@@ -0,0 +1,2234 @@
1
+ #!/usr/bin/env python3
2
+ """meu — MEU Universal Package & Project Manager for Windows 10 & Linux."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import difflib
8
+ import importlib.util
9
+ import json
10
+ import os
11
+ import re
12
+ import shutil
13
+ import stat
14
+ import subprocess
15
+ import sys
16
+ import sysconfig
17
+ import tempfile
18
+ import urllib.error
19
+ import urllib.request
20
+ import venv
21
+ import zipfile
22
+ from dataclasses import dataclass
23
+ from datetime import datetime, timezone
24
+ from pathlib import Path
25
+ from typing import Any, Callable, Mapping
26
+
27
+ __version__ = "1.0.0"
28
+
29
+ DEFAULT_OWNER = "meucak"
30
+
31
+ MEUCAK_CATALOG: dict[str, dict[str, Any]] = {
32
+ "perf": {
33
+ "name": "perf",
34
+ "aliases": [],
35
+ "kind": "python-cli",
36
+ "description": "Sıfır bağımlılıklı ultra hafif terminal görev yöneticisi (CPU/RAM/GPU/Sıcaklık).",
37
+ "entrypoints": [{"name": "perf", "target_type": "python_script", "script": "perf.py"}],
38
+ "port": None,
39
+ "apt_hints": [],
40
+ "platforms": ["linux"],
41
+ },
42
+ "sortingen": {
43
+ "name": "sortingen",
44
+ "aliases": [],
45
+ "kind": "python-cli",
46
+ "description": "Klasörleri dosya tipi (--doctype), kategori (--category) veya tarihe (--date) göre düzenleyen akıllı CLI aracı.",
47
+ "entrypoints": [{"name": "sortingen", "target_type": "python_script", "script": "sortingen.py"}],
48
+ "port": None,
49
+ "apt_hints": [],
50
+ "platforms": ["linux", "windows"],
51
+ },
52
+ "recep": {
53
+ "name": "recep",
54
+ "aliases": ["cs-bomb", "monster-claw"],
55
+ "kind": "pyqt-gui",
56
+ "description": "Masaüstü canavar gözü widget'ı ve sesli retro CS C4 bomba imha simülatörü.",
57
+ "entrypoints": [
58
+ {"name": "recep", "target_type": "python_script", "script": "cs_bomb_game.py", "gui": True},
59
+ {"name": "cs-bomb", "target_type": "python_script", "script": "cs_bomb_game.py", "gui": True},
60
+ {"name": "monster-claw", "target_type": "python_script", "script": "monster_claw_widget.py", "gui": True},
61
+ ],
62
+ "port": None,
63
+ "apt_hints": ["python3-pyqt6", "alsa-utils"],
64
+ "platforms": ["linux", "windows"],
65
+ },
66
+ "borfek": {
67
+ "name": "borfek",
68
+ "aliases": [],
69
+ "kind": "web-service",
70
+ "description": "Ağ bağımsız, Cloudflare & P2P tabanlı sıfır-merkez şifreli mesajlaşma ve dosya paylaşım platformu.",
71
+ "entrypoints": [{"name": "borfek", "target_type": "shell_pair", "port": 8093, "gui": True}],
72
+ "port": 8093,
73
+ "apt_hints": ["docker.io", "docker-compose-plugin"],
74
+ "platforms": ["linux", "windows"],
75
+ },
76
+ "tessera": {
77
+ "name": "tessera",
78
+ "aliases": [],
79
+ "kind": "web-service",
80
+ "description": "Markdown editörü, FTS5 arama, Bilgi Grafiği, Spatial Canvas, Kanban ve FSRS tekrar stüdyosu.",
81
+ "entrypoints": [{"name": "tessera", "target_type": "docker_web", "port": 8092, "gui": True}],
82
+ "port": 8092,
83
+ "apt_hints": ["docker.io", "docker-compose-plugin"],
84
+ "platforms": ["linux", "windows"],
85
+ },
86
+ "toshi-camera": {
87
+ "name": "toshi-camera",
88
+ "aliases": ["kamera"],
89
+ "kind": "pyqt-gui",
90
+ "description": "PyQt6 masaüstü kamera stüdyosu ve QR kodlu telefon kamera/mikrofon köprüsü.",
91
+ "entrypoints": [
92
+ {
93
+ "name": "toshi-camera",
94
+ "target_type": "python_module",
95
+ "module": "toshi_camera.main",
96
+ "pythonpath": "src",
97
+ "gui": True,
98
+ },
99
+ {
100
+ "name": "kamera",
101
+ "target_type": "python_module",
102
+ "module": "toshi_camera.main",
103
+ "pythonpath": "src",
104
+ "gui": True,
105
+ },
106
+ ],
107
+ "port": None,
108
+ "apt_hints": ["python3-pyqt6", "python3-opencv", "python3-numpy", "python3-websockets", "ffmpeg", "v4l-utils"],
109
+ "platforms": ["linux"],
110
+ },
111
+ "fil": {
112
+ "name": "fil",
113
+ "aliases": [],
114
+ "kind": "web-service",
115
+ "description": "Cloudflare Quick Tunnel, Tailscale ve LAN destekli evrensel dosya aktarımı ve sesli not köprüsü.",
116
+ "entrypoints": [{"name": "fil", "target_type": "shell_pair", "port": 8090, "gui": True}],
117
+ "port": 8090,
118
+ "apt_hints": ["docker.io", "docker-compose-plugin"],
119
+ "platforms": ["linux", "windows"],
120
+ },
121
+ "fleet-deck": {
122
+ "name": "fleet-deck",
123
+ "aliases": [],
124
+ "kind": "web-service",
125
+ "description": "Kasa, Toshi ve Quasimodo makineleri için sıfır-bulut çoklu cihaz görev kontrol panosu.",
126
+ "entrypoints": [{"name": "fleet-deck", "target_type": "shell_pair", "port": 8091, "gui": True}],
127
+ "port": 8091,
128
+ "apt_hints": ["docker.io", "docker-compose-plugin"],
129
+ "platforms": ["linux", "windows"],
130
+ },
131
+ "kush": {
132
+ "name": "kush",
133
+ "aliases": ["aura-lan", "saksogan"],
134
+ "kind": "web-service",
135
+ "description": "Yerel ağ ve Tailscale üzerinden sıfır gecikmeli mesajlaşma, pano ve dosya paylaşımı.",
136
+ "entrypoints": [{"name": "kush", "target_type": "shell_pair", "port": 8088, "gui": True}],
137
+ "port": 8088,
138
+ "apt_hints": ["docker.io", "docker-compose-plugin"],
139
+ "platforms": ["linux", "windows"],
140
+ },
141
+ "pdf-studio": {
142
+ "name": "pdf-studio",
143
+ "aliases": [],
144
+ "kind": "static-web",
145
+ "description": "Çevrimdışı çalışabilen PDF oluşturucu ve görsel PDF düzenleyici PWA web uygulaması.",
146
+ "entrypoints": [{"name": "pdf-studio", "target_type": "static_web", "gui": True}],
147
+ "port": None,
148
+ "apt_hints": [],
149
+ "platforms": ["linux", "windows"],
150
+ },
151
+ "antigravity-mobile-app": {
152
+ "name": "antigravity-mobile-app",
153
+ "aliases": ["makrotakip"],
154
+ "kind": "static-web",
155
+ "description": "Capacitor tabanlı MakroTakip mobil/web uygulaması.",
156
+ "entrypoints": [{"name": "antigravity-mobile-app", "target_type": "static_web", "gui": True}],
157
+ "port": None,
158
+ "apt_hints": [],
159
+ "platforms": ["linux", "windows"],
160
+ },
161
+ "MouseWithBorders-Android": {
162
+ "name": "MouseWithBorders-Android",
163
+ "aliases": ["mwb", "mousewithborders", "mouse-with-borders"],
164
+ "kind": "python-gui",
165
+ "description": "Windows PC ve Android cihazlar arasında yerel Wi-Fi UDP üzerinden <1ms fare/klavye paylaşımı.",
166
+ "entrypoints": [
167
+ {"name": "mwb", "target_type": "python_script", "script": "mouse_with_borders.py", "gui": True},
168
+ {"name": "mouse-with-borders", "target_type": "python_script", "script": "mouse_with_borders.py", "gui": True},
169
+ ],
170
+ "port": None,
171
+ "apt_hints": [],
172
+ "platforms": ["windows", "linux"],
173
+ },
174
+ }
175
+
176
+ ALIAS_MAP: dict[str, str] = {}
177
+ for _canonical_name, _meta in MEUCAK_CATALOG.items():
178
+ ALIAS_MAP[_canonical_name.lower()] = _canonical_name
179
+ for _alias in _meta.get("aliases", []):
180
+ ALIAS_MAP[_alias.lower()] = _canonical_name
181
+ ALIAS_MAP.setdefault("cluckbeat", "dancing-chicken")
182
+
183
+
184
+ @dataclass(frozen=True)
185
+ class TargetSpec:
186
+ owner: str
187
+ repo: str
188
+ branch: str | None
189
+ clone_url: str
190
+ zip_url: str
191
+ html_url: str
192
+ is_known_meucak: bool
193
+
194
+
195
+ def _canonicalize_repo_name(owner: str, repo: str) -> str:
196
+ if owner.lower() == DEFAULT_OWNER.lower():
197
+ return ALIAS_MAP.get(repo.lower(), repo)
198
+ return repo
199
+
200
+
201
+ def _clean_repo_segment(segment: str) -> str:
202
+ cleaned = segment.strip().strip("/")
203
+ if cleaned.endswith(".git"):
204
+ cleaned = cleaned[:-4]
205
+ return cleaned
206
+
207
+
208
+ def resolve_target(raw: str) -> TargetSpec:
209
+ """Normalize a project name, alias, owner/repo, or GitHub URL into a TargetSpec."""
210
+ text = (raw or "").strip().strip('"').strip("'").strip()
211
+ if not text:
212
+ raise ValueError("Proje adı veya GitHub bağlantısı boş olamaz.")
213
+
214
+ branch: str | None = None
215
+ owner = DEFAULT_OWNER
216
+ repo = ""
217
+
218
+ # Handle SSH git@github.com:owner/repo.git
219
+ ssh_match = re.match(r"^git@github\.com:([^/]+)/(.+?)(?:@([^/@]+))?$", text, re.IGNORECASE)
220
+ if ssh_match:
221
+ owner = ssh_match.group(1).strip()
222
+ repo = _clean_repo_segment(ssh_match.group(2))
223
+ branch = ssh_match.group(3).strip() if ssh_match.group(3) else None
224
+ else:
225
+ # Strip protocol or github.com prefix if present
226
+ url_candidate = text
227
+ # Handle @branch at the end if not part of user@host
228
+ if "@" in url_candidate and not url_candidate.lower().startswith("git@"):
229
+ base_part, maybe_branch = url_candidate.rsplit("@", 1)
230
+ if maybe_branch and "/" not in maybe_branch:
231
+ url_candidate = base_part
232
+ branch = maybe_branch.strip()
233
+
234
+ url_candidate = re.sub(r"^https?://", "", url_candidate, flags=re.IGNORECASE)
235
+ if url_candidate.lower().startswith("www.github.com/"):
236
+ url_candidate = url_candidate[len("www.github.com/") :]
237
+ elif url_candidate.lower().startswith("github.com/"):
238
+ url_candidate = url_candidate[len("github.com/") :]
239
+ elif url_candidate.lower() == "github.com":
240
+ raise ValueError(f"Geçersiz GitHub bağlantısı: {raw}")
241
+
242
+ parts = [p for p in url_candidate.strip("/").split("/") if p]
243
+ if not parts:
244
+ raise ValueError(f"Geçersiz proje hedefi: {raw}")
245
+
246
+ if len(parts) == 1:
247
+ owner = DEFAULT_OWNER
248
+ repo = _clean_repo_segment(parts[0])
249
+ else:
250
+ owner = parts[0].strip()
251
+ repo = _clean_repo_segment(parts[1])
252
+ if len(parts) >= 4 and parts[2].lower() in ("tree", "releases"):
253
+ tree_branch = "/".join(parts[3:]).strip("/")
254
+ if tree_branch and not branch:
255
+ branch = tree_branch
256
+
257
+ if not owner or not repo or any(ch in repo for ch in (" ", "\\", ":", "?", "*")):
258
+ raise ValueError(f"Geçersiz proje hedefi: {raw}")
259
+
260
+ repo = _canonicalize_repo_name(owner, repo)
261
+ is_known_meucak = owner.lower() == DEFAULT_OWNER.lower() and repo in MEUCAK_CATALOG
262
+ clone_url = f"https://github.com/{owner}/{repo}.git"
263
+ html_url = f"https://github.com/{owner}/{repo}"
264
+ if branch:
265
+ zip_url = f"https://codeload.github.com/{owner}/{repo}/zip/refs/heads/{branch}"
266
+ else:
267
+ zip_url = f"https://api.github.com/repos/{owner}/{repo}/zipball"
268
+
269
+ return TargetSpec(
270
+ owner=owner,
271
+ repo=repo,
272
+ branch=branch,
273
+ clone_url=clone_url,
274
+ zip_url=zip_url,
275
+ html_url=html_url,
276
+ is_known_meucak=is_known_meucak,
277
+ )
278
+
279
+
280
+ def suggest_similar_repos(name: str, catalog_names: list[str] | None = None) -> list[str]:
281
+ """Return likely matching repo names from the catalog and alias map."""
282
+ query = (name or "").strip().lower()
283
+ if not query:
284
+ return []
285
+ pool = list(catalog_names) if catalog_names is not None else list(MEUCAK_CATALOG.keys())
286
+ lower_to_canonical = {item.lower(): item for item in pool}
287
+ for alias, target in ALIAS_MAP.items():
288
+ if target in pool or catalog_names is None:
289
+ lower_to_canonical.setdefault(alias, target)
290
+
291
+ matches = difflib.get_close_matches(query, list(lower_to_canonical.keys()), n=5, cutoff=0.45)
292
+ seen: list[str] = []
293
+ for key in matches:
294
+ canonical = lower_to_canonical[key]
295
+ if canonical not in seen:
296
+ seen.append(canonical)
297
+
298
+ # Also include substring matches if fewer than 3
299
+ for key, canonical in lower_to_canonical.items():
300
+ if query in key and canonical not in seen:
301
+ seen.append(canonical)
302
+ return seen[:5]
303
+
304
+
305
+ def get_meu_paths(
306
+ env: Mapping[str, str] | None = None,
307
+ platform_name: str | None = None,
308
+ ) -> dict[str, Path]:
309
+ """Compute all filesystem directories used by meu in an OS-independent way."""
310
+ environ = env if env is not None else os.environ
311
+ plat = platform_name if platform_name is not None else os.name
312
+
313
+ if plat == "nt":
314
+ raw_user_home = environ.get("USERPROFILE") or environ.get("HOME") or str(Path.home())
315
+ else:
316
+ raw_user_home = environ.get("HOME") or str(Path.home())
317
+ user_home = Path(raw_user_home).expanduser()
318
+
319
+ has_custom_meu_home = bool(environ.get("MEU_HOME", "").strip())
320
+ if has_custom_meu_home:
321
+ home = Path(environ["MEU_HOME"]).expanduser()
322
+ else:
323
+ home = user_home / ".meu"
324
+
325
+ internal_bin_dir = home / "bin"
326
+
327
+ custom_bin_dir = environ.get("MEU_BIN_DIR", "").strip()
328
+ if custom_bin_dir:
329
+ bin_dir = Path(custom_bin_dir).expanduser()
330
+ elif plat == "nt" or has_custom_meu_home:
331
+ bin_dir = internal_bin_dir
332
+ else:
333
+ bin_dir = user_home / ".local" / "bin"
334
+
335
+ custom_desktop_dir = environ.get("MEU_DESKTOP_DIR", "").strip()
336
+ if custom_desktop_dir:
337
+ desktop_dir = Path(custom_desktop_dir).expanduser()
338
+ elif has_custom_meu_home:
339
+ desktop_dir = home / "desktop"
340
+ elif plat == "nt":
341
+ desktop_dir = user_home / "Desktop"
342
+ else:
343
+ desktop_dir = user_home / ".local" / "share" / "applications"
344
+
345
+ return {
346
+ "home": home,
347
+ "core_dir": home / "core",
348
+ "apps_dir": home / "apps",
349
+ "cache_dir": home / "cache",
350
+ "internal_bin_dir": internal_bin_dir,
351
+ "bin_dir": bin_dir,
352
+ "registry_file": home / "registry.json",
353
+ "desktop_dir": desktop_dir,
354
+ }
355
+
356
+
357
+ def _handle_remove_readonly(func: Callable[..., Any], path: str, exc_info: Any) -> None:
358
+ """Clear read-only attribute (Windows .git pack files) and retry removal."""
359
+ try:
360
+ os.chmod(path, stat.S_IWRITE | stat.S_IREAD)
361
+ except OSError:
362
+ pass
363
+ func(path)
364
+
365
+
366
+ def rmtree_safe(path: Path) -> None:
367
+ """Recursively delete a directory tree, handling read-only files on Windows & Linux."""
368
+ target = Path(path)
369
+ if not target.exists() and not target.is_symlink():
370
+ return
371
+ if target.is_symlink() or target.is_file():
372
+ try:
373
+ os.chmod(target, stat.S_IWRITE | stat.S_IREAD)
374
+ except OSError:
375
+ pass
376
+ target.unlink()
377
+ return
378
+
379
+ if sys.version_info >= (3, 12):
380
+ shutil.rmtree(target, onexc=_handle_remove_readonly)
381
+ else:
382
+ shutil.rmtree(target, onerror=_handle_remove_readonly)
383
+
384
+
385
+ class Registry:
386
+ """Atomic JSON registry storing installed meu applications and metadata."""
387
+
388
+ def __init__(self, registry_file: Path) -> None:
389
+ self.registry_file = Path(registry_file)
390
+
391
+ def _empty_state(self) -> dict[str, Any]:
392
+ return {"schema_version": 1, "apps": {}}
393
+
394
+ def load(self) -> dict[str, Any]:
395
+ if not self.registry_file.exists():
396
+ return self._empty_state()
397
+ try:
398
+ raw = self.registry_file.read_text(encoding="utf-8")
399
+ data = json.loads(raw)
400
+ if not isinstance(data, dict) or not isinstance(data.get("apps"), dict):
401
+ return self._empty_state()
402
+ return data
403
+ except (OSError, json.JSONDecodeError):
404
+ return self._empty_state()
405
+
406
+ def save(self, data: dict[str, Any]) -> None:
407
+ self.registry_file.parent.mkdir(parents=True, exist_ok=True)
408
+ fd, tmp_name = tempfile.mkstemp(
409
+ dir=str(self.registry_file.parent),
410
+ prefix=".registry_",
411
+ suffix=".tmp",
412
+ )
413
+ tmp_path = Path(tmp_name)
414
+ try:
415
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
416
+ json.dump(data, handle, indent=2, ensure_ascii=False)
417
+ handle.write("\n")
418
+ os.replace(tmp_path, self.registry_file)
419
+ except Exception:
420
+ if tmp_path.exists():
421
+ tmp_path.unlink()
422
+ raise
423
+
424
+ def _resolve_key(self, apps: dict[str, Any], name: str) -> str | None:
425
+ if name in apps:
426
+ return name
427
+ target_lower = name.lower()
428
+ canonical = ALIAS_MAP.get(target_lower, name).lower()
429
+ for existing_key in apps:
430
+ if existing_key.lower() in (target_lower, canonical):
431
+ return existing_key
432
+ return None
433
+
434
+ def get_app(self, name: str) -> dict[str, Any] | None:
435
+ data = self.load()
436
+ apps = data["apps"]
437
+ key = self._resolve_key(apps, name)
438
+ return apps.get(key) if key is not None else None
439
+
440
+ def set_app(self, name: str, record: dict[str, Any]) -> None:
441
+ data = self.load()
442
+ existing_key = self._resolve_key(data["apps"], name)
443
+ if existing_key and existing_key != name:
444
+ del data["apps"][existing_key]
445
+ data["apps"][name] = record
446
+ self.save(data)
447
+
448
+ def remove_app(self, name: str) -> dict[str, Any] | None:
449
+ data = self.load()
450
+ key = self._resolve_key(data["apps"], name)
451
+ if key is None:
452
+ return None
453
+ removed = data["apps"].pop(key)
454
+ self.save(data)
455
+ return removed
456
+
457
+ def list_apps(self) -> list[dict[str, Any]]:
458
+ data = self.load()
459
+ return [data["apps"][k] for k in sorted(data["apps"], key=str.lower)]
460
+
461
+
462
+ def extract_zip_root_stripped(zip_path: Path, dest_dir: Path) -> str:
463
+ """Safely extract a GitHub archive ZIP into dest_dir, stripping its single top-level directory."""
464
+ dest = Path(dest_dir)
465
+ dest.mkdir(parents=True, exist_ok=True)
466
+ dest_resolved = dest.resolve()
467
+
468
+ top_dirs: set[str] = set()
469
+ with zipfile.ZipFile(zip_path, "r") as zf:
470
+ members = zf.infolist()
471
+ for member in members:
472
+ norm = member.filename.replace("\\", "/")
473
+ if norm.startswith("/") or ".." in Path(norm).parts:
474
+ raise ValueError(f"Güvensiz ZIP yolu tespit edildi: {member.filename}")
475
+ first_part = norm.split("/", 1)[0]
476
+ if first_part:
477
+ top_dirs.add(first_part)
478
+
479
+ strip_prefix = ""
480
+ if len(top_dirs) == 1:
481
+ sole_root = next(iter(top_dirs))
482
+ has_root_slash = any(
483
+ m.filename.replace("\\", "/").startswith(f"{sole_root}/") for m in members
484
+ )
485
+ if has_root_slash:
486
+ strip_prefix = f"{sole_root}/"
487
+
488
+ for member in members:
489
+ rel_name = member.filename.replace("\\", "/")
490
+ if strip_prefix and rel_name.startswith(strip_prefix):
491
+ rel_name = rel_name[len(strip_prefix) :]
492
+ elif strip_prefix and rel_name.rstrip("/") == strip_prefix.rstrip("/"):
493
+ continue
494
+
495
+ if not rel_name or rel_name == "/":
496
+ continue
497
+
498
+ target_path = (dest / rel_name).resolve()
499
+ try:
500
+ target_path.relative_to(dest_resolved)
501
+ except ValueError as exc:
502
+ raise ValueError(f"ZIP hedef dizin dışına çıkıyor: {member.filename}") from exc
503
+
504
+ if member.is_dir():
505
+ target_path.mkdir(parents=True, exist_ok=True)
506
+ continue
507
+
508
+ target_path.parent.mkdir(parents=True, exist_ok=True)
509
+ with zf.open(member, "r") as src, open(target_path, "wb") as dst:
510
+ shutil.copyfileobj(src, dst)
511
+
512
+ unix_mode = (member.external_attr >> 16) & 0o777
513
+ if os.name != "nt" and (unix_mode & 0o111):
514
+ os.chmod(target_path, unix_mode | 0o644)
515
+
516
+ return strip_prefix.rstrip("/")
517
+
518
+
519
+ def _git_version_info(repo_dir: Path) -> str:
520
+ try:
521
+ proc = subprocess.run(
522
+ ["git", "-C", str(repo_dir), "rev-parse", "--short", "HEAD"],
523
+ capture_output=True,
524
+ text=True,
525
+ timeout=10,
526
+ check=True,
527
+ )
528
+ sha = proc.stdout.strip()
529
+ if sha:
530
+ return sha
531
+ except Exception:
532
+ pass
533
+ return datetime.now(timezone.utc).strftime("%Y%m%d")
534
+
535
+
536
+ def _build_zip_candidates(spec: TargetSpec) -> list[str]:
537
+ if spec.zip_url and spec.branch:
538
+ return [spec.zip_url]
539
+ candidates: list[str] = []
540
+ if spec.zip_url:
541
+ candidates.append(spec.zip_url)
542
+ candidates.extend(
543
+ [
544
+ f"https://codeload.github.com/{spec.owner}/{spec.repo}/zip/refs/heads/main",
545
+ f"https://codeload.github.com/{spec.owner}/{spec.repo}/zip/refs/heads/master",
546
+ ]
547
+ )
548
+ return list(dict.fromkeys(candidates))
549
+
550
+
551
+ def download_repo(
552
+ spec: TargetSpec,
553
+ dest_dir: Path,
554
+ prefer_git: bool = True,
555
+ cache_dir: Path | None = None,
556
+ opener: Callable[..., Any] | None = None,
557
+ ) -> dict[str, str]:
558
+ """Download a repository into dest_dir via git clone or GitHub ZIP fallback."""
559
+ dest = Path(dest_dir)
560
+ dest.parent.mkdir(parents=True, exist_ok=True)
561
+ staging = dest.parent / f".staging_{dest.name}_{os.getpid()}"
562
+ rmtree_safe(staging)
563
+
564
+ git_bin = shutil.which("git") if prefer_git else None
565
+ last_error = ""
566
+
567
+ if git_bin:
568
+ cmd = [git_bin, "clone", "--depth", "1"]
569
+ if spec.branch:
570
+ cmd.extend(["--branch", spec.branch])
571
+ cmd.extend([spec.clone_url, str(staging)])
572
+ try:
573
+ proc = subprocess.run(cmd, capture_output=True, text=True, timeout=180)
574
+ if proc.returncode == 0:
575
+ version = _git_version_info(staging)
576
+ rmtree_safe(dest)
577
+ os.replace(staging, dest)
578
+ return {"method": "git", "version": version}
579
+ last_error = (proc.stderr or proc.stdout or "").strip()
580
+ rmtree_safe(staging)
581
+ except Exception as exc:
582
+ last_error = str(exc)
583
+ rmtree_safe(staging)
584
+
585
+ # Do not try GitHub HTTP fallback for local file:// clones used in tests
586
+ if spec.clone_url.startswith("file://"):
587
+ raise RuntimeError(f"Git klonlama başarısız oldu: {last_error}")
588
+
589
+ http_open = opener if opener is not None else urllib.request.urlopen
590
+ zip_candidates = _build_zip_candidates(spec)
591
+ cache_root = cache_dir if cache_dir is not None else dest.parent / ".cache"
592
+ cache_root.mkdir(parents=True, exist_ok=True)
593
+ zip_file = cache_root / f"{spec.owner}_{spec.repo}.zip"
594
+
595
+ downloaded = False
596
+ not_found_count = 0
597
+ for url in zip_candidates:
598
+ req = urllib.request.Request(
599
+ url,
600
+ headers={"User-Agent": f"meu/{__version__} (+https://github.com/meucak)"},
601
+ )
602
+ try:
603
+ with http_open(req, timeout=60) as resp:
604
+ payload = resp.read()
605
+ if not payload:
606
+ continue
607
+ zip_file.write_bytes(payload)
608
+ downloaded = True
609
+ break
610
+ except urllib.error.HTTPError as exc:
611
+ if exc.code == 404:
612
+ not_found_count += 1
613
+ last_error = f"HTTP {exc.code}: {url}"
614
+ except Exception as exc:
615
+ last_error = str(exc)
616
+
617
+ if not downloaded:
618
+ if not_found_count == len(zip_candidates) and spec.owner.lower() == DEFAULT_OWNER.lower():
619
+ suggestions = suggest_similar_repos(spec.repo)
620
+ hint = f" Benzer projeler: {', '.join(suggestions)}" if suggestions else ""
621
+ raise RuntimeError(f"GitHub deposu bulunamadı: {spec.owner}/{spec.repo}.{hint}")
622
+ raise RuntimeError(f"Proje indirilemedi ({spec.html_url}): {last_error}")
623
+
624
+ try:
625
+ staging.mkdir(parents=True, exist_ok=True)
626
+ root_tag = extract_zip_root_stripped(zip_file, staging)
627
+ rmtree_safe(dest)
628
+ os.replace(staging, dest)
629
+ version = root_tag.split("-")[-1][:7] if "-" in root_tag else datetime.now(timezone.utc).strftime("%Y%m%d")
630
+ return {"method": "zip", "version": version}
631
+ finally:
632
+ rmtree_safe(staging)
633
+ if zip_file.exists():
634
+ try:
635
+ zip_file.unlink()
636
+ except OSError:
637
+ pass
638
+
639
+
640
+ def _find_python_gui_hint(app_dir: Path) -> bool:
641
+ for py_file in app_dir.glob("*.py"):
642
+ try:
643
+ text = py_file.read_text(encoding="utf-8", errors="ignore")[:4000]
644
+ except OSError:
645
+ continue
646
+ if any(mod in text for mod in ("PyQt6", "PyQt5", "PySide6", "tkinter")):
647
+ return True
648
+ return False
649
+
650
+
651
+ def _find_primary_python_scripts(app_dir: Path, repo_name: str) -> list[str]:
652
+ skip = {"setup.py", "conftest.py"}
653
+ py_files = [
654
+ p.name
655
+ for p in sorted(app_dir.glob("*.py"))
656
+ if p.is_file() and not p.name.startswith("test_") and not p.name.startswith(".meu_") and p.name not in skip
657
+ ]
658
+ if not py_files:
659
+ return []
660
+ norm_repo = repo_name.lower().replace("-", "_")
661
+ preferred = [
662
+ f"{repo_name}.py",
663
+ f"{norm_repo}.py",
664
+ "main.py",
665
+ "app.py",
666
+ "cli.py",
667
+ "run.py",
668
+ ]
669
+ for candidate in preferred:
670
+ for existing in py_files:
671
+ if existing.lower() == candidate.lower():
672
+ return [existing]
673
+ if len(py_files) == 1:
674
+ return py_files
675
+ # Prefer scripts containing __main__ guard
676
+ main_scripts = []
677
+ for name in py_files:
678
+ try:
679
+ txt = (app_dir / name).read_text(encoding="utf-8", errors="ignore")
680
+ except OSError:
681
+ continue
682
+ if '__name__ == "__main__"' in txt or "__name__ == '__main__'" in txt:
683
+ main_scripts.append(name)
684
+ return main_scripts[:1] if main_scripts else [py_files[0]]
685
+
686
+
687
+ def _detect_shell_pair(app_dir: Path, name: str) -> tuple[Path | None, Path | None]:
688
+ sh_candidates = [
689
+ app_dir / f"{name}-linux.sh",
690
+ app_dir / f"{name}.sh",
691
+ app_dir / "run.sh",
692
+ ]
693
+ bat_candidates = [
694
+ app_dir / f"{name}-windows.bat",
695
+ app_dir / f"{name}.bat",
696
+ app_dir / "run.bat",
697
+ ]
698
+ sh_path = next((p for p in sh_candidates if p.is_file()), None)
699
+ bat_path = next((p for p in bat_candidates if p.is_file()), None)
700
+ return sh_path, bat_path
701
+
702
+
703
+ def _extract_port_from_compose(app_dir: Path) -> int | None:
704
+ for fname in ("docker-compose.yml", "compose.yml"):
705
+ fpath = app_dir / fname
706
+ if fpath.is_file():
707
+ try:
708
+ content = fpath.read_text(encoding="utf-8", errors="ignore")
709
+ match = re.search(r'["\']?(?:127\.0\.0\.1:)?(\d{4,5}):\d{4,5}["\']?', content)
710
+ if match:
711
+ return int(match.group(1))
712
+ except OSError:
713
+ pass
714
+ return None
715
+
716
+
717
+ def inspect_project(app_dir: Path, repo_name: str) -> dict[str, Any]:
718
+ """Inspect a cloned/extracted repository and build a cross-platform install plan."""
719
+ app_path = Path(app_dir)
720
+ canonical = ALIAS_MAP.get(repo_name.lower(), repo_name)
721
+ req_file = app_path / "requirements.txt"
722
+ has_req = req_file.is_file()
723
+ has_compose = (app_path / "docker-compose.yml").is_file() or (app_path / "compose.yml").is_file()
724
+
725
+ # Tier 1: Explicit meu.json manifest inside the repository
726
+ manifest_file = app_path / "meu.json"
727
+ if manifest_file.is_file():
728
+ try:
729
+ manifest = json.loads(manifest_file.read_text(encoding="utf-8"))
730
+ if isinstance(manifest, dict) and manifest.get("commands"):
731
+ kind = str(manifest.get("kind", "python-cli"))
732
+ needs_venv = bool(manifest.get("needs_venv", has_req))
733
+ return {
734
+ "name": manifest.get("name", canonical),
735
+ "kind": kind,
736
+ "needs_venv": needs_venv,
737
+ "requirements_file": req_file if has_req else None,
738
+ "commands": list(manifest["commands"]),
739
+ "has_docker_compose": has_compose,
740
+ "desktop_entry": manifest.get("desktop_entry"),
741
+ "description": manifest.get("description", ""),
742
+ "port": manifest.get("port"),
743
+ "apt_hints": list(manifest.get("apt_hints", [])),
744
+ }
745
+ except (OSError, json.JSONDecodeError):
746
+ pass
747
+
748
+ # Tier 2: Built-in MEUCAK_CATALOG recipe
749
+ if canonical in MEUCAK_CATALOG:
750
+ recipe = MEUCAK_CATALOG[canonical]
751
+ kind = recipe["kind"]
752
+ commands: list[dict[str, Any]] = []
753
+ sh_path, bat_path = _detect_shell_pair(app_path, canonical)
754
+
755
+ for entry in recipe["entrypoints"]:
756
+ cmd = dict(entry)
757
+ if cmd["target_type"] == "shell_pair":
758
+ if sh_path:
759
+ cmd["sh_script"] = sh_path.name
760
+ if bat_path:
761
+ cmd["bat_script"] = bat_path.name
762
+ elif cmd["target_type"] == "static_web":
763
+ if (app_path / "index.html").is_file():
764
+ cmd["html_path"] = "index.html"
765
+ elif (app_path / "www" / "index.html").is_file():
766
+ cmd["html_path"] = "www/index.html"
767
+ commands.append(cmd)
768
+
769
+ needs_venv = has_req or kind == "pyqt-gui"
770
+ is_gui = any(c.get("gui") for c in commands)
771
+ desktop_entry = None
772
+ if is_gui and commands:
773
+ desktop_entry = {
774
+ "name": canonical,
775
+ "comment": recipe["description"],
776
+ "command": commands[0]["name"],
777
+ "icon": "applications-internet" if kind in ("web-service", "static-web") else "utilities-terminal",
778
+ "categories": "Network;Utility;" if kind in ("web-service", "static-web") else "Utility;",
779
+ }
780
+
781
+ return {
782
+ "name": canonical,
783
+ "kind": kind,
784
+ "needs_venv": needs_venv,
785
+ "requirements_file": req_file if has_req else None,
786
+ "commands": commands,
787
+ "has_docker_compose": has_compose,
788
+ "desktop_entry": desktop_entry,
789
+ "description": recipe["description"],
790
+ "port": recipe.get("port"),
791
+ "apt_hints": list(recipe.get("apt_hints", [])),
792
+ }
793
+
794
+ # Tier 3: Universal Heuristic Auto-Detector for new/external repositories
795
+ cmd_slug = canonical.lower()
796
+ sh_path, bat_path = _detect_shell_pair(app_path, canonical)
797
+ if sh_path is None and bat_path is None:
798
+ sh_path, bat_path = _detect_shell_pair(app_path, cmd_slug)
799
+
800
+ if has_compose or (sh_path and bat_path):
801
+ port = _extract_port_from_compose(app_path)
802
+ cmd_dict: dict[str, Any] = {
803
+ "name": cmd_slug,
804
+ "target_type": "shell_pair" if (sh_path or bat_path) else "docker_web",
805
+ "port": port or 8080,
806
+ "gui": True,
807
+ }
808
+ if sh_path:
809
+ cmd_dict["sh_script"] = sh_path.name
810
+ if bat_path:
811
+ cmd_dict["bat_script"] = bat_path.name
812
+ return {
813
+ "name": canonical,
814
+ "kind": "web-service",
815
+ "needs_venv": False,
816
+ "requirements_file": None,
817
+ "commands": [cmd_dict],
818
+ "has_docker_compose": has_compose,
819
+ "desktop_entry": {
820
+ "name": canonical,
821
+ "comment": f"{canonical} servisi",
822
+ "command": cmd_slug,
823
+ "icon": "applications-internet",
824
+ "categories": "Network;Utility;",
825
+ },
826
+ "description": f"{canonical} web/Docker uygulaması",
827
+ "port": port,
828
+ "apt_hints": ["docker.io", "docker-compose-plugin"] if has_compose else [],
829
+ }
830
+
831
+ # Check Python package under src/<pkg>/main.py or __main__.py
832
+ src_dir = app_path / "src"
833
+ if src_dir.is_dir():
834
+ for pkg_dir in sorted(src_dir.iterdir()):
835
+ if pkg_dir.is_dir() and ((pkg_dir / "main.py").is_file() or (pkg_dir / "__main__.py").is_file()):
836
+ mod_suffix = "main" if (pkg_dir / "main.py").is_file() else "__main__"
837
+ mod_name = f"{pkg_dir.name}.{mod_suffix}" if mod_suffix == "main" else pkg_dir.name
838
+ is_gui = _find_python_gui_hint(pkg_dir)
839
+ kind = "pyqt-gui" if is_gui else "python-cli"
840
+ return {
841
+ "name": canonical,
842
+ "kind": kind,
843
+ "needs_venv": has_req or is_gui,
844
+ "requirements_file": req_file if has_req else None,
845
+ "commands": [
846
+ {
847
+ "name": cmd_slug,
848
+ "target_type": "python_module",
849
+ "module": mod_name,
850
+ "pythonpath": "src",
851
+ "gui": is_gui,
852
+ }
853
+ ],
854
+ "has_docker_compose": False,
855
+ "desktop_entry": (
856
+ {
857
+ "name": canonical,
858
+ "comment": f"{canonical} masaüstü uygulaması",
859
+ "command": cmd_slug,
860
+ "icon": "utilities-terminal",
861
+ "categories": "Utility;",
862
+ }
863
+ if is_gui
864
+ else None
865
+ ),
866
+ "description": f"{canonical} Python uygulaması",
867
+ "port": None,
868
+ "apt_hints": [],
869
+ }
870
+
871
+ py_scripts = _find_primary_python_scripts(app_path, canonical)
872
+ if py_scripts:
873
+ is_gui = _find_python_gui_hint(app_path)
874
+ has_pyqt = any(
875
+ "PyQt" in (app_path / p).read_text(encoding="utf-8", errors="ignore")[:4000]
876
+ for p in py_scripts
877
+ )
878
+ if not has_pyqt and has_req:
879
+ req_txt = req_file.read_text(encoding="utf-8", errors="ignore")
880
+ has_pyqt = "PyQt" in req_txt or "PySide" in req_txt
881
+ kind = "pyqt-gui" if has_pyqt else ("python-gui" if is_gui else "python-cli")
882
+ return {
883
+ "name": canonical,
884
+ "kind": kind,
885
+ "needs_venv": has_req or has_pyqt,
886
+ "requirements_file": req_file if has_req else None,
887
+ "commands": [
888
+ {
889
+ "name": cmd_slug,
890
+ "target_type": "python_script",
891
+ "script": py_scripts[0],
892
+ "gui": is_gui,
893
+ }
894
+ ],
895
+ "has_docker_compose": False,
896
+ "desktop_entry": (
897
+ {
898
+ "name": canonical,
899
+ "comment": f"{canonical} uygulaması",
900
+ "command": cmd_slug,
901
+ "icon": "utilities-terminal",
902
+ "categories": "Utility;",
903
+ }
904
+ if is_gui
905
+ else None
906
+ ),
907
+ "description": f"{canonical} Python projesi",
908
+ "port": None,
909
+ "apt_hints": [],
910
+ }
911
+
912
+ # Static web app
913
+ for html_rel in ("index.html", "www/index.html", "public/index.html"):
914
+ if (app_path / html_rel).is_file():
915
+ return {
916
+ "name": canonical,
917
+ "kind": "static-web",
918
+ "needs_venv": False,
919
+ "requirements_file": None,
920
+ "commands": [
921
+ {
922
+ "name": cmd_slug,
923
+ "target_type": "static_web",
924
+ "html_path": html_rel,
925
+ "gui": True,
926
+ }
927
+ ],
928
+ "has_docker_compose": False,
929
+ "desktop_entry": {
930
+ "name": canonical,
931
+ "comment": f"{canonical} web uygulaması",
932
+ "command": cmd_slug,
933
+ "icon": "applications-internet",
934
+ "categories": "Network;Utility;",
935
+ },
936
+ "description": f"{canonical} web uygulaması",
937
+ "port": None,
938
+ "apt_hints": [],
939
+ }
940
+
941
+ return {
942
+ "name": canonical,
943
+ "kind": "script",
944
+ "needs_venv": has_req,
945
+ "requirements_file": req_file if has_req else None,
946
+ "commands": [],
947
+ "has_docker_compose": False,
948
+ "desktop_entry": None,
949
+ "description": f"{canonical} deposu",
950
+ "port": None,
951
+ "apt_hints": [],
952
+ }
953
+
954
+
955
+ def _patch_fcntl_cross_platform(text: str, lock_filename: str) -> tuple[str, bool]:
956
+ """Make Unix fcntl lock usage safe on Windows while preserving Linux flock behavior."""
957
+ changed = False
958
+ if "except ImportError:" not in text and re.search(r"^\s*import fcntl\s*$", text, re.MULTILINE):
959
+ guard = (
960
+ "import os\n"
961
+ "import tempfile\n"
962
+ "try:\n"
963
+ " import fcntl\n"
964
+ "except ImportError:\n"
965
+ " fcntl = None"
966
+ )
967
+ text = re.sub(r"^\s*import fcntl\s*$", guard, text, count=1, flags=re.MULTILINE)
968
+ changed = True
969
+
970
+ old_lock_open = f'open("/tmp/{lock_filename}", "w")'
971
+ new_lock_open = f'open(os.path.join(tempfile.gettempdir(), "{lock_filename}"), "w")'
972
+ if old_lock_open in text:
973
+ text = text.replace(old_lock_open, new_lock_open)
974
+ changed = True
975
+
976
+ text, n_subs = re.subn(
977
+ r"^([ \t]*)fcntl\.flock\((.+)\)[ \t]*$",
978
+ r"\1if fcntl is not None:\n\1 fcntl.flock(\2)",
979
+ text,
980
+ flags=re.MULTILINE,
981
+ )
982
+ # Prevent double-wrapping if already guarded
983
+ text = text.replace(
984
+ "if fcntl is not None:\n if fcntl is not None:\n",
985
+ "if fcntl is not None:\n",
986
+ )
987
+ if n_subs > 0:
988
+ changed = True
989
+ return text, changed
990
+
991
+
992
+ def apply_compat_patches(app_dir: Path, repo_name: str) -> list[str]:
993
+ """Apply cross-platform compatibility adapters (e.g., recep Windows/Linux fixes)."""
994
+ app_path = Path(app_dir)
995
+ notes: list[str] = []
996
+ canonical = ALIAS_MAP.get(repo_name.lower(), repo_name)
997
+
998
+ is_recep = canonical.lower() == "recep" or (
999
+ (app_path / "cs_bomb_game.py").is_file() and (app_path / "monster_claw_widget.py").is_file()
1000
+ )
1001
+ if not is_recep:
1002
+ return notes
1003
+
1004
+ # 1. Copy c4_skin.jpeg to ~/.local/share/cs-bomb when running live (outside isolated MEU_HOME tests)
1005
+ local_skin = app_path / "c4_skin.jpeg"
1006
+ if local_skin.is_file() and not os.environ.get("MEU_HOME"):
1007
+ try:
1008
+ share_dir = Path.home() / ".local" / "share" / "cs-bomb"
1009
+ share_dir.mkdir(parents=True, exist_ok=True)
1010
+ shutil.copy2(local_skin, share_dir / "c4_skin.jpeg")
1011
+ notes.append("c4_skin.jpeg ~/.local/share/cs-bomb/ altına kopyalandı")
1012
+ except OSError:
1013
+ pass
1014
+
1015
+ # 2. Patch cs_bomb_game.py (SKIN_PATH local fallback + cross-platform fcntl lock)
1016
+ bomb_file = app_path / "cs_bomb_game.py"
1017
+ if bomb_file.is_file():
1018
+ src = bomb_file.read_text(encoding="utf-8")
1019
+ orig = src
1020
+ old_skin_line = 'SKIN_PATH = os.path.expanduser("~/.local/share/cs-bomb/c4_skin.jpeg")'
1021
+ new_skin_block = (
1022
+ '_LOCAL_SKIN = os.path.join(os.path.dirname(os.path.abspath(__file__)), "c4_skin.jpeg")\n'
1023
+ 'SKIN_PATH = _LOCAL_SKIN if os.path.exists(_LOCAL_SKIN) else os.path.expanduser("~/.local/share/cs-bomb/c4_skin.jpeg")'
1024
+ )
1025
+ if old_skin_line in src and "_LOCAL_SKIN" not in src:
1026
+ src = src.replace(old_skin_line, new_skin_block, 1)
1027
+ src, _ = _patch_fcntl_cross_platform(src, "cs_bomb_game.lock")
1028
+ if src != orig:
1029
+ bomb_file.write_text(src, encoding="utf-8")
1030
+ notes.append("cs_bomb_game.py çapraz platform (fcntl + skin) uyumlu hale getirildi")
1031
+
1032
+ # 3. Patch monster_claw_widget.py (cross-platform fcntl + dynamic cs_bomb_game.py launch)
1033
+ claw_file = app_path / "monster_claw_widget.py"
1034
+ if claw_file.is_file():
1035
+ src = claw_file.read_text(encoding="utf-8")
1036
+ orig = src
1037
+ src, _ = _patch_fcntl_cross_platform(src, "monster_claw_widget.lock")
1038
+ if '"/home/toshi/.local/bin/cs-bomb"' in src:
1039
+ if "import sys" not in src:
1040
+ src = "import sys\n" + src
1041
+ src = src.replace(
1042
+ '["/home/toshi/.local/bin/cs-bomb"]',
1043
+ '[sys.executable, os.path.join(os.path.dirname(os.path.abspath(__file__)), "cs_bomb_game.py")]',
1044
+ )
1045
+ if src != orig:
1046
+ claw_file.write_text(src, encoding="utf-8")
1047
+ notes.append("monster_claw_widget.py dinamik başlatıcı ve çapraz platform kilitle güncellendi")
1048
+
1049
+ # 4. Patch sound_fx.py (Windows winsound + Linux aplay/paplay/pw-play + local wav fallback)
1050
+ sound_file = app_path / "sound_fx.py"
1051
+ if sound_file.is_file():
1052
+ src = sound_file.read_text(encoding="utf-8")
1053
+ if "winsound" not in src:
1054
+ header_imports = ""
1055
+ if "import shutil" not in src:
1056
+ header_imports += "import shutil\n"
1057
+ if "import sys" not in src:
1058
+ header_imports += "import sys\n"
1059
+ if header_imports:
1060
+ src = header_imports + src
1061
+
1062
+ compat_play = (
1063
+ "\ndef _meu_find_wav(name):\n"
1064
+ " primary = os.path.join(SOUNDS_DIR, f\"{name}.wav\")\n"
1065
+ " if os.path.exists(primary):\n"
1066
+ " return primary\n"
1067
+ " local = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"sounds\", f\"{name}.wav\")\n"
1068
+ " if os.path.exists(local):\n"
1069
+ " return local\n"
1070
+ " try:\n"
1071
+ " ensure_sounds()\n"
1072
+ " except Exception:\n"
1073
+ " pass\n"
1074
+ " return primary if os.path.exists(primary) else None\n\n"
1075
+ "def play(name):\n"
1076
+ " wav_path = _meu_find_wav(name)\n"
1077
+ " if not wav_path:\n"
1078
+ " return\n"
1079
+ " if sys.platform == \"win32\":\n"
1080
+ " try:\n"
1081
+ " import winsound\n"
1082
+ " winsound.PlaySound(wav_path, winsound.SND_FILENAME | winsound.SND_ASYNC)\n"
1083
+ " except Exception:\n"
1084
+ " pass\n"
1085
+ " return\n"
1086
+ " for player, args in ((\"aplay\", [\"-q\"]), (\"paplay\", []), (\"pw-play\", [])):\n"
1087
+ " if shutil.which(player):\n"
1088
+ " try:\n"
1089
+ " subprocess.Popen([player, *args, wav_path], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n"
1090
+ " except Exception:\n"
1091
+ " pass\n"
1092
+ " return\n"
1093
+ )
1094
+ play_pattern = re.compile(
1095
+ r"def play\(name\):.*?(?=\nif __name__ ==|\Z)",
1096
+ re.DOTALL,
1097
+ )
1098
+ if play_pattern.search(src):
1099
+ src = play_pattern.sub(compat_play.lstrip("\n") + "\n", src, count=1)
1100
+ else:
1101
+ src = src.rstrip() + "\n" + compat_play
1102
+ sound_file.write_text(src, encoding="utf-8")
1103
+ notes.append("sound_fx.py Windows (winsound) ve Linux ses oynatıcıları için güncellendi")
1104
+
1105
+ return notes
1106
+
1107
+
1108
+ def _ensure_web_launcher_script(app_dir: Path, cmd_spec: dict[str, Any]) -> Path:
1109
+ """Create a tiny cross-platform Python launcher for static_web / docker_web targets."""
1110
+ cmd_name = cmd_spec["name"]
1111
+ safe_name = re.sub(r"[^a-zA-Z0-9_-]", "_", cmd_name)
1112
+ launcher = app_dir / f".meu_launch_{safe_name}.py"
1113
+ target_type = cmd_spec["target_type"]
1114
+
1115
+ if target_type == "static_web":
1116
+ rel_html = cmd_spec.get("html_path", "index.html")
1117
+ code = (
1118
+ "from pathlib import Path\n"
1119
+ "import webbrowser\n"
1120
+ f"target = Path(__file__).resolve().parent / {rel_html!r}\n"
1121
+ "print(f'Açılıyor: {target}')\n"
1122
+ "webbrowser.open(target.as_uri())\n"
1123
+ )
1124
+ else:
1125
+ port = int(cmd_spec.get("port") or 8080)
1126
+ code = (
1127
+ "import shutil, subprocess, sys, urllib.request, webbrowser\n"
1128
+ "from pathlib import Path\n"
1129
+ f"url = 'http://127.0.0.1:{port}'\n"
1130
+ "app_dir = Path(__file__).resolve().parent\n"
1131
+ "def is_up():\n"
1132
+ " try:\n"
1133
+ " with urllib.request.urlopen(url, timeout=1.5):\n"
1134
+ " return True\n"
1135
+ " except Exception:\n"
1136
+ " return False\n"
1137
+ "if not is_up() and shutil.which('docker'):\n"
1138
+ " print(f'Docker servisi başlatılıyor ({app_dir})...')\n"
1139
+ " subprocess.run(['docker', 'compose', 'up', '-d'], cwd=str(app_dir))\n"
1140
+ "print(f'Tarayıcıda açılıyor: {url}')\n"
1141
+ "webbrowser.open(url)\n"
1142
+ )
1143
+ launcher.write_text(code, encoding="utf-8")
1144
+ return launcher
1145
+
1146
+
1147
+ def _build_posix_shim_content(app_dir: Path, cmd_spec: dict[str, Any], python_exe: Path) -> str:
1148
+ ttype = cmd_spec["target_type"]
1149
+ lines = ["#!/usr/bin/env bash"]
1150
+ py_path_rel = cmd_spec.get("pythonpath")
1151
+ if py_path_rel:
1152
+ lines.append(f'export PYTHONPATH="{app_dir / py_path_rel}${{PYTHONPATH:+:$PYTHONPATH}}"')
1153
+
1154
+ if ttype == "python_script":
1155
+ script_path = app_dir / cmd_spec["script"]
1156
+ lines.append(f'exec "{python_exe}" "{script_path}" "$@"')
1157
+ elif ttype == "python_module":
1158
+ lines.append(f'exec "{python_exe}" -m "{cmd_spec["module"]}" "$@"')
1159
+ elif ttype == "shell_pair" and cmd_spec.get("sh_script"):
1160
+ sh_path = app_dir / cmd_spec["sh_script"]
1161
+ lines.append(f'exec bash "{sh_path}" "$@"')
1162
+ else:
1163
+ launcher = _ensure_web_launcher_script(app_dir, cmd_spec)
1164
+ lines.append(f'exec "{python_exe}" "{launcher}" "$@"')
1165
+
1166
+ return "\n".join(lines) + "\n"
1167
+
1168
+
1169
+ def _build_windows_cmd_content(app_dir: Path, cmd_spec: dict[str, Any], python_exe: Path) -> str:
1170
+ ttype = cmd_spec["target_type"]
1171
+ lines = ["@echo off", "setlocal"]
1172
+ py_path_rel = cmd_spec.get("pythonpath")
1173
+ if py_path_rel:
1174
+ lines.append(f'set "PYTHONPATH={app_dir / py_path_rel};%PYTHONPATH%"')
1175
+
1176
+ if ttype == "python_script":
1177
+ script_path = app_dir / cmd_spec["script"]
1178
+ lines.append(f'"{python_exe}" "{script_path}" %*')
1179
+ elif ttype == "python_module":
1180
+ lines.append(f'"{python_exe}" -m "{cmd_spec["module"]}" %*')
1181
+ elif ttype == "shell_pair" and cmd_spec.get("bat_script"):
1182
+ bat_path = app_dir / cmd_spec["bat_script"]
1183
+ lines.append(f'call "{bat_path}" %*')
1184
+ else:
1185
+ launcher = _ensure_web_launcher_script(app_dir, cmd_spec)
1186
+ lines.append(f'"{python_exe}" "{launcher}" %*')
1187
+
1188
+ lines.append("exit /b %ERRORLEVEL%")
1189
+ return "\r\n".join(lines) + "\r\n"
1190
+
1191
+
1192
+ def _build_windows_ps1_content(app_dir: Path, cmd_spec: dict[str, Any], python_exe: Path) -> str:
1193
+ ttype = cmd_spec["target_type"]
1194
+ lines = []
1195
+ py_path_rel = cmd_spec.get("pythonpath")
1196
+ if py_path_rel:
1197
+ lines.append(f'$env:PYTHONPATH = "{app_dir / py_path_rel};" + $env:PYTHONPATH')
1198
+
1199
+ if ttype == "python_script":
1200
+ script_path = app_dir / cmd_spec["script"]
1201
+ lines.append(f'& "{python_exe}" "{script_path}" @args')
1202
+ elif ttype == "python_module":
1203
+ lines.append(f'& "{python_exe}" -m "{cmd_spec["module"]}" @args')
1204
+ elif ttype == "shell_pair" and cmd_spec.get("bat_script"):
1205
+ bat_path = app_dir / cmd_spec["bat_script"]
1206
+ lines.append(f'& cmd.exe /c "`"{bat_path}`"" @args')
1207
+ else:
1208
+ launcher = _ensure_web_launcher_script(app_dir, cmd_spec)
1209
+ lines.append(f'& "{python_exe}" "{launcher}" @args')
1210
+
1211
+ lines.append("exit $LASTEXITCODE")
1212
+ return "\r\n".join(lines) + "\r\n"
1213
+
1214
+
1215
+ def create_command_shims(
1216
+ bin_dir: Path,
1217
+ internal_bin_dir: Path,
1218
+ app_dir: Path,
1219
+ cmd_spec: dict[str, Any],
1220
+ python_exe: Path,
1221
+ platform_name: str | None = None,
1222
+ ) -> list[Path]:
1223
+ """Create executable CLI wrappers (POSIX bash on Linux, .cmd/.ps1/bash on Windows)."""
1224
+ plat = platform_name if platform_name is not None else os.name
1225
+ cmd_name = cmd_spec["name"]
1226
+ created: list[Path] = []
1227
+ target_dirs = [Path(bin_dir)]
1228
+ if Path(internal_bin_dir) != Path(bin_dir):
1229
+ target_dirs.append(Path(internal_bin_dir))
1230
+
1231
+ posix_text = _build_posix_shim_content(app_dir, cmd_spec, python_exe)
1232
+ win_cmd_text = _build_windows_cmd_content(app_dir, cmd_spec, python_exe) if plat == "nt" else ""
1233
+ win_ps1_text = _build_windows_ps1_content(app_dir, cmd_spec, python_exe) if plat == "nt" else ""
1234
+
1235
+ for d in target_dirs:
1236
+ d.mkdir(parents=True, exist_ok=True)
1237
+ sh_file = d / cmd_name
1238
+ sh_file.write_text(posix_text, encoding="utf-8")
1239
+ if os.name != "nt":
1240
+ os.chmod(sh_file, 0o755)
1241
+ created.append(sh_file)
1242
+
1243
+ if plat == "nt":
1244
+ cmd_file = d / f"{cmd_name}.cmd"
1245
+ cmd_file.write_text(win_cmd_text, encoding="utf-8")
1246
+ created.append(cmd_file)
1247
+
1248
+ ps1_file = d / f"{cmd_name}.ps1"
1249
+ ps1_file.write_text(win_ps1_text, encoding="utf-8")
1250
+ created.append(ps1_file)
1251
+
1252
+ return created
1253
+
1254
+
1255
+ def _supports_color() -> bool:
1256
+ if os.environ.get("NO_COLOR"):
1257
+ return False
1258
+ return hasattr(sys.stdout, "isatty") and sys.stdout.isatty()
1259
+
1260
+
1261
+ def _style(text: str, code: str) -> str:
1262
+ if not _supports_color():
1263
+ return text
1264
+ return f"\033[{code}m{text}\033[0m"
1265
+
1266
+
1267
+ def _info(msg: str) -> None:
1268
+ print(f"{_style('::', '1;36')} {msg}")
1269
+
1270
+
1271
+ def _ok(msg: str) -> None:
1272
+ print(f"{_style('[OK]', '1;32')} {msg}")
1273
+
1274
+
1275
+ def _warn(msg: str) -> None:
1276
+ print(f"{_style('[!]', '1;33')} {msg}")
1277
+
1278
+
1279
+ def _err(msg: str) -> None:
1280
+ print(f"{_style('[HATA]', '1;31')} {msg}", file=sys.stderr)
1281
+
1282
+
1283
+ def _configure_utf8_streams() -> None:
1284
+ for stream in (sys.stdout, sys.stderr):
1285
+ reconf = getattr(stream, "reconfigure", None)
1286
+ if callable(reconf):
1287
+ try:
1288
+ reconf(encoding="utf-8", errors="replace")
1289
+ except Exception:
1290
+ pass
1291
+
1292
+
1293
+ def _parse_requirement_modules(req_file: Path) -> list[str]:
1294
+ modules: list[str] = []
1295
+ pkg_to_import = {
1296
+ "pyqt6": "PyQt6",
1297
+ "pyqt5": "PyQt5",
1298
+ "pyside6": "PySide6",
1299
+ "opencv-python": "cv2",
1300
+ "pillow": "PIL",
1301
+ "pyyaml": "yaml",
1302
+ }
1303
+ for line in req_file.read_text(encoding="utf-8", errors="ignore").splitlines():
1304
+ clean = line.split("#", 1)[0].strip()
1305
+ if not clean or clean.startswith("-"):
1306
+ continue
1307
+ pkg = re.split(r"[<>=!~;\[]", clean, maxsplit=1)[0].strip()
1308
+ if pkg:
1309
+ modules.append(pkg_to_import.get(pkg.lower(), pkg.replace("-", "_")))
1310
+ return modules
1311
+
1312
+
1313
+ def _modules_importable(python_exe: Path, modules: list[str]) -> bool:
1314
+ if not modules:
1315
+ return True
1316
+ check_code = "; ".join(f"import {m}" for m in modules)
1317
+ try:
1318
+ proc = subprocess.run(
1319
+ [str(python_exe), "-c", check_code],
1320
+ capture_output=True,
1321
+ text=True,
1322
+ timeout=15,
1323
+ )
1324
+ return proc.returncode == 0
1325
+ except Exception:
1326
+ return False
1327
+
1328
+
1329
+ def _venv_has_pip(venv_python: Path) -> bool:
1330
+ try:
1331
+ proc = subprocess.run(
1332
+ [str(venv_python), "-m", "pip", "--version"],
1333
+ capture_output=True,
1334
+ text=True,
1335
+ timeout=10,
1336
+ )
1337
+ return proc.returncode == 0
1338
+ except Exception:
1339
+ return False
1340
+
1341
+
1342
+ def _bootstrap_pip_in_venv(venv_python: Path) -> bool:
1343
+ """Download get-pip.py into a temp file and install pip inside venv when ensurepip is absent."""
1344
+ get_pip_url = "https://bootstrap.pypa.io/get-pip.py"
1345
+ req = urllib.request.Request(get_pip_url, headers={"User-Agent": f"meu/{__version__}"})
1346
+ fd, tmp_name = tempfile.mkstemp(prefix="meu_get_pip_", suffix=".py")
1347
+ tmp_path = Path(tmp_name)
1348
+ try:
1349
+ os.close(fd)
1350
+ with urllib.request.urlopen(req, timeout=30) as resp:
1351
+ tmp_path.write_bytes(resp.read())
1352
+ proc = subprocess.run(
1353
+ [str(venv_python), str(tmp_path), "--disable-pip-version-check", "-q"],
1354
+ capture_output=True,
1355
+ text=True,
1356
+ timeout=180,
1357
+ )
1358
+ return proc.returncode == 0 and _venv_has_pip(venv_python)
1359
+ except Exception:
1360
+ return False
1361
+ finally:
1362
+ if tmp_path.exists():
1363
+ try:
1364
+ tmp_path.unlink()
1365
+ except OSError:
1366
+ pass
1367
+
1368
+
1369
+ def _setup_python_env(app_dir: Path, plan: dict[str, Any], no_deps: bool) -> tuple[Path, bool]:
1370
+ """Create isolated .venv and install requirements when needed."""
1371
+ sys_python = Path(sys.executable)
1372
+ if no_deps or not plan.get("needs_venv"):
1373
+ return sys_python, False
1374
+
1375
+ venv_dir = app_dir / ".venv"
1376
+ venv_python = venv_dir / ("Scripts/python.exe" if os.name == "nt" else "bin/python")
1377
+ req_file: Path | None = plan.get("requirements_file")
1378
+
1379
+ if not venv_python.is_file():
1380
+ _info("İzole Python sanal ortamı (.venv) oluşturuluyor...")
1381
+ has_ensurepip = importlib.util.find_spec("ensurepip") is not None
1382
+ sys_site_pkgs = os.name != "nt"
1383
+ created = False
1384
+ last_exc: BaseException | None = None
1385
+
1386
+ if has_ensurepip:
1387
+ try:
1388
+ venv.EnvBuilder(with_pip=True, system_site_packages=sys_site_pkgs).create(str(venv_dir))
1389
+ created = venv_python.is_file()
1390
+ except (Exception, SystemExit) as exc:
1391
+ last_exc = exc
1392
+ rmtree_safe(venv_dir)
1393
+
1394
+ if not created:
1395
+ try:
1396
+ venv.EnvBuilder(with_pip=False, system_site_packages=sys_site_pkgs).create(str(venv_dir))
1397
+ created = venv_python.is_file()
1398
+ except (Exception, SystemExit) as exc:
1399
+ last_exc = exc
1400
+ rmtree_safe(venv_dir)
1401
+
1402
+ if not created:
1403
+ if req_file and _modules_importable(sys_python, _parse_requirement_modules(req_file)):
1404
+ _warn(f".venv oluşturulamadı ({last_exc}); sistem Python bağımlılıkları zaten mevcut, devam ediliyor.")
1405
+ return sys_python, False
1406
+ raise RuntimeError(
1407
+ f"Sanal ortam (.venv) oluşturulamadı: {last_exc}. Linux'ta 'sudo apt install python3-venv' gerekebilir."
1408
+ )
1409
+
1410
+ if req_file and req_file.is_file():
1411
+ modules = _parse_requirement_modules(req_file)
1412
+ if os.name != "nt" and _modules_importable(venv_python, modules):
1413
+ _info("Python bağımlılıkları sistem/sanal ortamda zaten karşılanıyor.")
1414
+ return venv_python, True
1415
+
1416
+ if not _venv_has_pip(venv_python):
1417
+ uv_bin = shutil.which("uv")
1418
+ if uv_bin:
1419
+ _info(f"Bağımlılıklar uv ile kuruluyor: {req_file.name}")
1420
+ uv_proc = subprocess.run(
1421
+ [uv_bin, "pip", "install", "--python", str(venv_python), "-q", "-r", str(req_file)],
1422
+ capture_output=True,
1423
+ text=True,
1424
+ timeout=300,
1425
+ )
1426
+ if uv_proc.returncode == 0:
1427
+ return venv_python, True
1428
+
1429
+ _info("ensurepip bulunamadı; sanal ortam için pip önyükleniyor...")
1430
+ if not _bootstrap_pip_in_venv(venv_python):
1431
+ raise RuntimeError(
1432
+ "Sanal ortam içinde pip bulunamadı (python3-venv eksik). "
1433
+ "Çözüm: 'sudo apt install -y python3-venv' veya '--no-deps' kullanın."
1434
+ )
1435
+
1436
+ _info(f"Bağımlılıklar kuruluyor: {req_file.name}")
1437
+ proc = subprocess.run(
1438
+ [str(venv_python), "-m", "pip", "install", "--disable-pip-version-check", "-q", "-r", str(req_file)],
1439
+ capture_output=True,
1440
+ text=True,
1441
+ timeout=300,
1442
+ )
1443
+ if proc.returncode != 0:
1444
+ if _modules_importable(venv_python, modules):
1445
+ _warn("pip kurulumu uyarı verdi ancak gerekli modüller içe aktarılabiliyor; devam ediliyor.")
1446
+ else:
1447
+ detail = (proc.stderr or proc.stdout or "").strip()
1448
+ raise RuntimeError(f"pip bağımlılık kurulumu başarısız oldu:\n{detail}")
1449
+
1450
+ return venv_python, True
1451
+
1452
+
1453
+ def _create_desktop_shortcuts(
1454
+ paths: dict[str, Path],
1455
+ plan: dict[str, Any],
1456
+ repo_name: str,
1457
+ ) -> list[Path]:
1458
+ """Create .desktop launcher on Linux or .lnk shortcut on Windows Desktop when appropriate."""
1459
+ entry = plan.get("desktop_entry")
1460
+ if not entry:
1461
+ return []
1462
+
1463
+ desktop_dir = paths["desktop_dir"]
1464
+ desktop_dir.mkdir(parents=True, exist_ok=True)
1465
+ cmd_name = entry["command"]
1466
+ display_name = entry.get("name", repo_name)
1467
+ comment = entry.get("comment", display_name)
1468
+ created: list[Path] = []
1469
+
1470
+ if os.name != "nt":
1471
+ exec_path = paths["bin_dir"] / cmd_name
1472
+ desktop_file = desktop_dir / f"meu-{repo_name.lower()}.desktop"
1473
+ content = (
1474
+ "[Desktop Entry]\n"
1475
+ "Type=Application\n"
1476
+ f"Name={display_name}\n"
1477
+ f"Comment={comment}\n"
1478
+ f"Exec={exec_path}\n"
1479
+ f"Icon={entry.get('icon', 'utilities-terminal')}\n"
1480
+ "Terminal=false\n"
1481
+ f"Categories={entry.get('categories', 'Utility;')}\n"
1482
+ )
1483
+ desktop_file.write_text(content, encoding="utf-8")
1484
+ os.chmod(desktop_file, 0o755)
1485
+ created.append(desktop_file)
1486
+ elif not os.environ.get("MEU_HOME"):
1487
+ target_cmd = paths["bin_dir"] / f"{cmd_name}.cmd"
1488
+ lnk_path = desktop_dir / f"{display_name}.lnk"
1489
+ ps_cmd = (
1490
+ "$ws = New-Object -ComObject WScript.Shell; "
1491
+ f"$s = $ws.CreateShortcut('{str(lnk_path).replace(chr(39), chr(39)*2)}'); "
1492
+ f"$s.TargetPath = '{str(target_cmd).replace(chr(39), chr(39)*2)}'; "
1493
+ f"$s.WorkingDirectory = '{str(paths['apps_dir'] / repo_name).replace(chr(39), chr(39)*2)}'; "
1494
+ f"$s.Description = '{str(comment).replace(chr(39), chr(39)*2)}'; "
1495
+ "$s.Save()"
1496
+ )
1497
+ ps_bin = shutil.which("powershell") or shutil.which("pwsh")
1498
+ if ps_bin:
1499
+ proc = subprocess.run([ps_bin, "-NoProfile", "-Command", ps_cmd], capture_output=True, text=True, timeout=20)
1500
+ if proc.returncode == 0 and lnk_path.exists():
1501
+ created.append(lnk_path)
1502
+
1503
+ return created
1504
+
1505
+
1506
+ def _check_missing_apt_packages(apt_hints: list[str]) -> list[str]:
1507
+ if os.name == "nt" or not apt_hints or not shutil.which("dpkg-query"):
1508
+ return []
1509
+ missing: list[str] = []
1510
+ for pkg in apt_hints:
1511
+ proc = subprocess.run(
1512
+ ["dpkg-query", "-W", "-f=${Status}", pkg],
1513
+ capture_output=True,
1514
+ text=True,
1515
+ )
1516
+ if proc.returncode != 0 or "install ok installed" not in proc.stdout:
1517
+ missing.append(pkg)
1518
+ return missing
1519
+
1520
+
1521
+ def _path_contains_dir(target_dir: Path) -> bool:
1522
+ norm_target = os.path.normcase(os.path.normpath(str(target_dir)))
1523
+ for part in os.environ.get("PATH", "").split(os.pathsep):
1524
+ if not part:
1525
+ continue
1526
+ if os.path.normcase(os.path.normpath(part)) == norm_target:
1527
+ return True
1528
+ return False
1529
+
1530
+
1531
+ def _ensure_user_path(bin_dir: Path) -> bool:
1532
+ """Idempotently add bin_dir to the user's persistent PATH on Linux or Windows."""
1533
+ if os.environ.get("MEU_HOME"):
1534
+ return False
1535
+
1536
+ if os.name == "nt":
1537
+ try:
1538
+ import ctypes
1539
+ import winreg
1540
+
1541
+ target_str = str(bin_dir)
1542
+ with winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Environment", 0, winreg.KEY_READ | winreg.KEY_WRITE) as key:
1543
+ try:
1544
+ current_val, val_type = winreg.QueryValueEx(key, "Path")
1545
+ except FileNotFoundError:
1546
+ current_val, val_type = "", winreg.REG_EXPAND_SZ
1547
+ entries = [p for p in current_val.split(";") if p.strip()]
1548
+ norm_target = os.path.normcase(os.path.normpath(target_str))
1549
+ already = any(os.path.normcase(os.path.normpath(p)) == norm_target for p in entries)
1550
+ if not already:
1551
+ entries.append(target_str)
1552
+ new_val = ";".join(entries)
1553
+ winreg.SetValueEx(key, "Path", 0, val_type or winreg.REG_EXPAND_SZ, new_val)
1554
+ try:
1555
+ ctypes.windll.user32.SendMessageTimeoutW(
1556
+ 0xFFFF, 0x001A, 0, "Environment", 0x0002, 2000, None
1557
+ )
1558
+ except Exception:
1559
+ pass
1560
+ if not _path_contains_dir(bin_dir):
1561
+ os.environ["PATH"] = f"{target_str};{os.environ.get('PATH', '')}"
1562
+ return not already
1563
+ except Exception as exc:
1564
+ _warn(f"Windows PATH otomatik güncellenemedi: {exc}")
1565
+ return False
1566
+
1567
+ # POSIX: ~/.bashrc and ~/.profile
1568
+ export_block = (
1569
+ "\n# >>> meu path >>>\n"
1570
+ f'if [ -d "{bin_dir}" ] && [[ ":$PATH:" != *":{bin_dir}:"* ]]; then\n'
1571
+ f' export PATH="{bin_dir}:$PATH"\n'
1572
+ "fi\n"
1573
+ "# <<< meu path <<<\n"
1574
+ )
1575
+ updated_any = False
1576
+ for rc_name in (".bashrc", ".profile"):
1577
+ rc_path = Path.home() / rc_name
1578
+ try:
1579
+ existing = rc_path.read_text(encoding="utf-8") if rc_path.exists() else ""
1580
+ if "# >>> meu path >>>" not in existing and str(bin_dir) not in existing:
1581
+ rc_path.write_text(existing.rstrip("\n") + export_block, encoding="utf-8")
1582
+ updated_any = True
1583
+ except OSError:
1584
+ pass
1585
+ return updated_any
1586
+
1587
+
1588
+ def _get_pip_scripts_dir(
1589
+ bin_dir: Path,
1590
+ internal_bin_dir: Path,
1591
+ *,
1592
+ ignore_meu_home: bool = False,
1593
+ ) -> Path | None:
1594
+ """Return writable Python Scripts/bin dir on PATH if pip installed meu there."""
1595
+ if os.environ.get("MEU_HOME") and not ignore_meu_home:
1596
+ return None
1597
+
1598
+ excluded = {bin_dir.resolve(), internal_bin_dir.resolve()}
1599
+ candidates: list[Path] = []
1600
+ for scheme in (None, "nt_user" if os.name == "nt" else "posix_user"):
1601
+ try:
1602
+ raw = sysconfig.get_path("scripts") if scheme is None else sysconfig.get_path("scripts", scheme=scheme)
1603
+ except Exception:
1604
+ raw = None
1605
+ if raw:
1606
+ candidates.append(Path(raw))
1607
+
1608
+ if sys.argv and sys.argv[0]:
1609
+ try:
1610
+ argv_dir = Path(sys.argv[0]).resolve().parent
1611
+ candidates.append(argv_dir)
1612
+ except OSError:
1613
+ pass
1614
+
1615
+ for cand in candidates:
1616
+ try:
1617
+ resolved = cand.resolve()
1618
+ except OSError:
1619
+ continue
1620
+ if resolved in excluded or not resolved.is_dir():
1621
+ continue
1622
+ if not _path_contains_dir(resolved) or not os.access(resolved, os.W_OK):
1623
+ continue
1624
+ if any((resolved / name).exists() for name in ("meu.exe", "meu.cmd", "meu", "meucak.exe", "meucak")):
1625
+ return resolved
1626
+ return None
1627
+
1628
+
1629
+ def _install_single(
1630
+ raw_target: str,
1631
+ *,
1632
+ force: bool = False,
1633
+ no_deps: bool = False,
1634
+ no_desktop: bool = False,
1635
+ branch_override: str | None = None,
1636
+ docker_up: bool = False,
1637
+ prefer_git: bool = True,
1638
+ ) -> int:
1639
+ paths = get_meu_paths()
1640
+ registry = Registry(paths["registry_file"])
1641
+
1642
+ spec = resolve_target(raw_target)
1643
+ if branch_override:
1644
+ spec = TargetSpec(
1645
+ owner=spec.owner,
1646
+ repo=spec.repo,
1647
+ branch=branch_override,
1648
+ clone_url=spec.clone_url,
1649
+ zip_url=f"https://codeload.github.com/{spec.owner}/{spec.repo}/zip/refs/heads/{branch_override}",
1650
+ html_url=spec.html_url,
1651
+ is_known_meucak=spec.is_known_meucak,
1652
+ )
1653
+
1654
+ existing = registry.get_app(spec.repo)
1655
+ app_dir = paths["apps_dir"] / spec.repo
1656
+ if existing and app_dir.exists() and not force:
1657
+ cmds = ", ".join(existing.get("commands", [])) or spec.repo
1658
+ _ok(f"{spec.repo} zaten kurulu (sürüm: {existing.get('version', '?')}, komutlar: {cmds}).")
1659
+ _info(f"Güncellemek için: meu update {spec.repo} | Yeniden kurmak için: meu install {spec.repo} --force")
1660
+ return 0
1661
+
1662
+ _info(f"{spec.owner}/{spec.repo} indiriliyor ({spec.html_url})...")
1663
+ dl_meta = download_repo(
1664
+ spec,
1665
+ app_dir,
1666
+ prefer_git=prefer_git,
1667
+ cache_dir=paths["cache_dir"],
1668
+ )
1669
+ _ok(f"İndirildi ({dl_meta['method']} • {dl_meta['version']}) -> {app_dir}")
1670
+
1671
+ compat_notes = apply_compat_patches(app_dir, spec.repo)
1672
+ for note in compat_notes:
1673
+ _info(f"Uyumluluk uyarlaması: {note}")
1674
+
1675
+ plan = inspect_project(app_dir, spec.repo)
1676
+ python_exe, has_venv = _setup_python_env(app_dir, plan, no_deps=no_deps)
1677
+
1678
+ # Remove stale shims if reinstalling/updating
1679
+ if existing:
1680
+ for old_shim in existing.get("shims", []):
1681
+ p = Path(old_shim)
1682
+ if p.exists() or p.is_symlink():
1683
+ try:
1684
+ p.unlink()
1685
+ except OSError:
1686
+ pass
1687
+
1688
+ pip_scripts_dir = _get_pip_scripts_dir(paths["bin_dir"], paths["internal_bin_dir"])
1689
+ all_shims: list[Path] = []
1690
+ seen_shims: set[Path] = set()
1691
+ for cmd_spec in plan["commands"]:
1692
+ shims = create_command_shims(
1693
+ paths["bin_dir"],
1694
+ paths["internal_bin_dir"],
1695
+ app_dir,
1696
+ cmd_spec,
1697
+ python_exe,
1698
+ )
1699
+ if pip_scripts_dir is not None:
1700
+ shims.extend(
1701
+ create_command_shims(
1702
+ pip_scripts_dir,
1703
+ pip_scripts_dir,
1704
+ app_dir,
1705
+ cmd_spec,
1706
+ python_exe,
1707
+ )
1708
+ )
1709
+ for s in shims:
1710
+ if s not in seen_shims:
1711
+ seen_shims.add(s)
1712
+ all_shims.append(s)
1713
+
1714
+ desktop_files: list[Path] = []
1715
+ if not no_desktop:
1716
+ desktop_files = _create_desktop_shortcuts(paths, plan, spec.repo)
1717
+
1718
+ if docker_up and plan.get("has_docker_compose"):
1719
+ docker_bin = shutil.which("docker")
1720
+ if docker_bin:
1721
+ _info(f"Docker servisi ayağa kaldırılıyor: {spec.repo}")
1722
+ subprocess.run([docker_bin, "compose", "up", "-d"], cwd=str(app_dir), check=False)
1723
+ else:
1724
+ _warn("Docker bulunamadı; sadece başlatıcı kısayolları kuruldu.")
1725
+
1726
+ now_iso = datetime.now(timezone.utc).isoformat(timespec="seconds")
1727
+ installed_at = existing.get("installed_at", now_iso) if existing else now_iso
1728
+ cmd_names = [c["name"] for c in plan["commands"]]
1729
+
1730
+ record = {
1731
+ "name": spec.repo,
1732
+ "owner": spec.owner,
1733
+ "html_url": spec.html_url,
1734
+ "branch": spec.branch,
1735
+ "method": dl_meta["method"],
1736
+ "version": dl_meta["version"],
1737
+ "kind": plan["kind"],
1738
+ "description": plan.get("description", ""),
1739
+ "app_dir": str(app_dir),
1740
+ "python_exe": str(python_exe),
1741
+ "commands": cmd_names,
1742
+ "shims": [str(p) for p in all_shims],
1743
+ "desktop_files": [str(p) for p in desktop_files],
1744
+ "has_venv": has_venv,
1745
+ "installed_at": installed_at,
1746
+ "updated_at": now_iso,
1747
+ }
1748
+ registry.set_app(spec.repo, record)
1749
+
1750
+ _ok(f"{spec.repo} başarıyla kuruldu!")
1751
+ if cmd_names:
1752
+ _info(f"Terminal komutu: {', '.join(cmd_names)}")
1753
+ if desktop_files:
1754
+ _info(f"Masaüstü kısayolu: {', '.join(str(p) for p in desktop_files)}")
1755
+
1756
+ missing_apt = _check_missing_apt_packages(plan.get("apt_hints", []))
1757
+ if missing_apt:
1758
+ _warn(f"Önerilen sistem paketleri eksik olabilir: sudo apt install -y {' '.join(missing_apt)}")
1759
+
1760
+ if not _path_contains_dir(paths["bin_dir"]):
1761
+ if _ensure_user_path(paths["bin_dir"]):
1762
+ _info(f"PATH otomatik güncellendi ({paths['bin_dir']}).")
1763
+ elif not os.environ.get("MEU_HOME"):
1764
+ _warn(f"'{paths['bin_dir']}' PATH içinde görünmüyor. Eklemek için: meu doctor --fix")
1765
+
1766
+ return 0
1767
+
1768
+
1769
+ def cmd_install(args: argparse.Namespace) -> int:
1770
+ exit_code = 0
1771
+ for target in args.targets:
1772
+ try:
1773
+ rc = _install_single(
1774
+ target,
1775
+ force=args.force,
1776
+ no_deps=args.no_deps,
1777
+ no_desktop=args.no_desktop,
1778
+ branch_override=args.branch,
1779
+ docker_up=args.docker,
1780
+ prefer_git=not args.zip,
1781
+ )
1782
+ if rc != 0:
1783
+ exit_code = rc
1784
+ except Exception as exc:
1785
+ _err(f"{target}: {exc}")
1786
+ exit_code = 1
1787
+ return exit_code
1788
+
1789
+
1790
+ def cmd_uninstall(args: argparse.Namespace) -> int:
1791
+ paths = get_meu_paths()
1792
+ registry = Registry(paths["registry_file"])
1793
+ exit_code = 0
1794
+
1795
+ for target in args.targets:
1796
+ record = registry.get_app(target)
1797
+ if record is None:
1798
+ try:
1799
+ spec = resolve_target(target)
1800
+ record = registry.get_app(spec.repo)
1801
+ except ValueError:
1802
+ record = None
1803
+
1804
+ if record is None:
1805
+ _err(f"Kurulu proje bulunamadı: {target}")
1806
+ exit_code = 1
1807
+ continue
1808
+
1809
+ for shim in record.get("shims", []):
1810
+ p = Path(shim)
1811
+ if p.exists() or p.is_symlink():
1812
+ try:
1813
+ p.unlink()
1814
+ except OSError as exc:
1815
+ _warn(f"Komut kaldırılamadı ({p}): {exc}")
1816
+
1817
+ for dfile in record.get("desktop_files", []):
1818
+ p = Path(dfile)
1819
+ if p.exists() or p.is_symlink():
1820
+ try:
1821
+ p.unlink()
1822
+ except OSError as exc:
1823
+ _warn(f"Kısayol kaldırılamadı ({p}): {exc}")
1824
+
1825
+ app_dir = Path(record["app_dir"])
1826
+ if app_dir.exists():
1827
+ rmtree_safe(app_dir)
1828
+
1829
+ registry.remove_app(record["name"])
1830
+ _ok(f"{record['name']} tamamen kaldırıldı.")
1831
+ return exit_code
1832
+
1833
+
1834
+ def cmd_update(args: argparse.Namespace) -> int:
1835
+ paths = get_meu_paths()
1836
+ registry = Registry(paths["registry_file"])
1837
+ targets = list(args.targets)
1838
+
1839
+ if args.all or not targets:
1840
+ installed = registry.list_apps()
1841
+ if not installed:
1842
+ _info("Güncellenecek kurulu proje yok.")
1843
+ return 0
1844
+ targets = [app["name"] for app in installed]
1845
+
1846
+ exit_code = 0
1847
+ for target in targets:
1848
+ rec = registry.get_app(target)
1849
+ src_ref = f"{rec['owner']}/{rec['name']}" if rec and rec.get("owner") else target
1850
+ try:
1851
+ rc = _install_single(
1852
+ src_ref,
1853
+ force=True,
1854
+ no_deps=args.no_deps,
1855
+ no_desktop=args.no_desktop,
1856
+ branch_override=rec.get("branch") if rec else None,
1857
+ )
1858
+ if rc != 0:
1859
+ exit_code = rc
1860
+ except Exception as exc:
1861
+ _err(f"{target} güncellenemedi: {exc}")
1862
+ exit_code = 1
1863
+ return exit_code
1864
+
1865
+
1866
+ def cmd_list(args: argparse.Namespace) -> int:
1867
+ paths = get_meu_paths()
1868
+ registry = Registry(paths["registry_file"])
1869
+ apps = registry.list_apps()
1870
+
1871
+ if getattr(args, "json", False):
1872
+ print(json.dumps(apps, indent=2, ensure_ascii=False))
1873
+ return 0
1874
+
1875
+ if not apps:
1876
+ _info("Henüz meu ile kurulmuş proje yok. Mevcut projeler için: meu search")
1877
+ return 0
1878
+
1879
+ rows = []
1880
+ for app in apps:
1881
+ app_exists = Path(app.get("app_dir", "")).is_dir()
1882
+ status = "Hazır" if app_exists else "Eksik"
1883
+ cmds = ", ".join(app.get("commands", [])) or "-"
1884
+ rows.append(
1885
+ (
1886
+ app.get("name", "?"),
1887
+ app.get("kind", "?"),
1888
+ cmds,
1889
+ app.get("version", "?"),
1890
+ app.get("method", "?"),
1891
+ status,
1892
+ )
1893
+ )
1894
+
1895
+ headers = ("PROJE", "TÜR", "KOMUTLAR", "SÜRÜM", "YÖNTEM", "DURUM")
1896
+ widths = [max(len(h), *(len(r[i]) for r in rows)) for i, h in enumerate(headers)]
1897
+ fmt = " ".join(f"{{:<{w}}}" for w in widths)
1898
+ print(_style(fmt.format(*headers), "1"))
1899
+ print(" ".join("-" * w for w in widths))
1900
+ for r in rows:
1901
+ print(fmt.format(*r))
1902
+ return 0
1903
+
1904
+
1905
+ def _fetch_live_meucak_repos(timeout: float = 4.0) -> list[dict[str, Any]]:
1906
+ url = f"https://api.github.com/users/{DEFAULT_OWNER}/repos?per_page=100&sort=updated"
1907
+ req = urllib.request.Request(
1908
+ url,
1909
+ headers={
1910
+ "User-Agent": f"meu/{__version__}",
1911
+ "Accept": "application/vnd.github+json",
1912
+ },
1913
+ )
1914
+ try:
1915
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
1916
+ payload = json.loads(resp.read().decode("utf-8"))
1917
+ if isinstance(payload, list):
1918
+ return [item for item in payload if isinstance(item, dict) and item.get("name")]
1919
+ except Exception:
1920
+ pass
1921
+ return []
1922
+
1923
+
1924
+ def cmd_search(args: argparse.Namespace) -> int:
1925
+ paths = get_meu_paths()
1926
+ registry = Registry(paths["registry_file"])
1927
+ installed_names = {app["name"].lower() for app in registry.list_apps()}
1928
+
1929
+ catalog: dict[str, dict[str, Any]] = {
1930
+ name: {
1931
+ "name": name,
1932
+ "kind": meta["kind"],
1933
+ "description": meta["description"],
1934
+ "aliases": meta.get("aliases", []),
1935
+ "commands": [e["name"] for e in meta.get("entrypoints", [])],
1936
+ }
1937
+ for name, meta in MEUCAK_CATALOG.items()
1938
+ }
1939
+
1940
+ if not args.offline:
1941
+ for repo in _fetch_live_meucak_repos():
1942
+ rname = repo["name"]
1943
+ if rname not in catalog and rname != ".github":
1944
+ catalog[rname] = {
1945
+ "name": rname,
1946
+ "kind": (repo.get("language") or "repo").lower(),
1947
+ "description": repo.get("description") or "GitHub deposu (otomatik algılama)",
1948
+ "aliases": [],
1949
+ "commands": [rname.lower()],
1950
+ }
1951
+ elif rname in catalog and not catalog[rname]["description"] and repo.get("description"):
1952
+ catalog[rname]["description"] = repo["description"]
1953
+
1954
+ query = (args.query or "").strip().lower()
1955
+ items = []
1956
+ for name in sorted(catalog, key=str.lower):
1957
+ entry = catalog[name]
1958
+ haystack = " ".join(
1959
+ [
1960
+ entry["name"],
1961
+ entry["description"],
1962
+ entry["kind"],
1963
+ " ".join(entry["aliases"]),
1964
+ " ".join(entry["commands"]),
1965
+ ]
1966
+ ).lower()
1967
+ if not query or query in haystack:
1968
+ items.append(entry)
1969
+
1970
+ if not items:
1971
+ suggestions = suggest_similar_repos(query, list(catalog.keys()))
1972
+ _warn(f"'{args.query}' için eşleşen proje bulunamadı.")
1973
+ if suggestions:
1974
+ _info(f"Bunu mu aradınız: {', '.join(suggestions)}")
1975
+ return 0
1976
+
1977
+ for entry in items:
1978
+ badge = _style("[KURULU]", "1;32") if entry["name"].lower() in installed_names else _style("[MEVCUT]", "0;36")
1979
+ alias_str = f" (diğer ad: {', '.join(entry['aliases'])})" if entry["aliases"] else ""
1980
+ print(f"{badge} {_style(entry['name'], '1')}{alias_str} [{entry['kind']}]")
1981
+ print(f" {entry['description']}")
1982
+ print(f" Kurulum: meu install {entry['name']}")
1983
+ return 0
1984
+
1985
+
1986
+ def cmd_info(args: argparse.Namespace) -> int:
1987
+ paths = get_meu_paths()
1988
+ registry = Registry(paths["registry_file"])
1989
+ spec = resolve_target(args.target)
1990
+ rec = registry.get_app(spec.repo)
1991
+ cat = MEUCAK_CATALOG.get(spec.repo)
1992
+
1993
+ print(_style(f"Proje: {spec.owner}/{spec.repo}", "1"))
1994
+ print(f"GitHub: {spec.html_url}")
1995
+ if cat:
1996
+ print(f"Tür: {cat['kind']}")
1997
+ print(f"Açıklama: {cat['description']}")
1998
+ if cat.get("aliases"):
1999
+ print(f"Kısa Adlar: {', '.join(cat['aliases'])}")
2000
+ print(f"Platformlar: {', '.join(cat.get('platforms', []))}")
2001
+ cmds = [e["name"] for e in cat.get("entrypoints", [])]
2002
+ if cmds:
2003
+ print(f"Komutlar: {', '.join(cmds)}")
2004
+ if cat.get("port"):
2005
+ print(f"Varsayılan Port: {cat['port']}")
2006
+ if rec:
2007
+ print(f"Durum: {_style('Kurulu', '1;32')} ({rec.get('version', '?')} • {rec.get('method', '?')})")
2008
+ print(f"Dizin: {rec.get('app_dir')}")
2009
+ print(f"Komutlar: {', '.join(rec.get('commands', []))}")
2010
+ if rec.get("desktop_files"):
2011
+ print(f"Kısayollar: {', '.join(rec['desktop_files'])}")
2012
+ else:
2013
+ print(f"Durum: Kurulu değil (kurmak için: meu install {spec.repo})")
2014
+ return 0
2015
+
2016
+
2017
+ def cmd_run(args: argparse.Namespace) -> int:
2018
+ paths = get_meu_paths()
2019
+ registry = Registry(paths["registry_file"])
2020
+ spec = resolve_target(args.target)
2021
+ rec = registry.get_app(spec.repo)
2022
+
2023
+ if rec is None or not Path(rec.get("app_dir", "")).is_dir():
2024
+ _info(f"{spec.repo} kurulu değil; önce otomatik indirip kuruluyor...")
2025
+ rc = _install_single(args.target)
2026
+ if rc != 0:
2027
+ return rc
2028
+ rec = registry.get_app(spec.repo)
2029
+ if rec is None:
2030
+ _err(f"{spec.repo} kurulumu doğrulanamadı.")
2031
+ return 1
2032
+
2033
+ commands = rec.get("commands", [])
2034
+ if not commands:
2035
+ _err(f"{rec['name']} için tanımlı çalıştırılabilir komut yok. Dizin: {rec.get('app_dir')}")
2036
+ return 1
2037
+
2038
+ primary_cmd = commands[0]
2039
+ if os.name == "nt":
2040
+ shim = paths["bin_dir"] / f"{primary_cmd}.cmd"
2041
+ cmd_list = ["cmd", "/c", str(shim), *args.extra_args]
2042
+ else:
2043
+ shim = paths["bin_dir"] / primary_cmd
2044
+ cmd_list = [str(shim), *args.extra_args]
2045
+
2046
+ if not shim.exists():
2047
+ _err(f"Başlatıcı bulunamadı: {shim}. Onarmak için: meu install {rec['name']} --force")
2048
+ return 1
2049
+
2050
+ proc = subprocess.run(cmd_list)
2051
+ return proc.returncode
2052
+
2053
+
2054
+ def cmd_doctor(args: argparse.Namespace) -> int:
2055
+ paths = get_meu_paths()
2056
+ registry = Registry(paths["registry_file"])
2057
+
2058
+ print(_style(f"meu v{__version__} Sistem Tanılama ({os.name})", "1"))
2059
+ print(f"MEU Ana Dizini : {paths['home']}")
2060
+ print(f"Uygulamalar : {paths['apps_dir']}")
2061
+ print(f"Komut Dizini : {paths['bin_dir']}")
2062
+ print(f"Kısayol Dizini : {paths['desktop_dir']}")
2063
+
2064
+ py_ok = sys.version_info >= (3, 8)
2065
+ print(f"Python : {sys.version.split()[0]} ({sys.executable}) [{'OK' if py_ok else 'ESKİ'}]")
2066
+
2067
+ git_bin = shutil.which("git")
2068
+ print(f"Git : {git_bin or 'Yok (ZIP yedek indirme kullanılacak)'}")
2069
+
2070
+ docker_bin = shutil.which("docker")
2071
+ print(f"Docker : {docker_bin or 'Yok (yalnızca konteyner servisleri için gerekli)'}")
2072
+
2073
+ in_path = _path_contains_dir(paths["bin_dir"])
2074
+ print(f"PATH Durumu : {'Hazır' if in_path else 'Eksik (' + str(paths['bin_dir']) + ')'}")
2075
+
2076
+ if args.fix:
2077
+ for key in ("home", "core_dir", "apps_dir", "cache_dir", "bin_dir", "internal_bin_dir", "desktop_dir"):
2078
+ paths[key].mkdir(parents=True, exist_ok=True)
2079
+ if _ensure_user_path(paths["bin_dir"]):
2080
+ _ok(f"PATH güncellendi: {paths['bin_dir']} (yeni terminalde aktif olur)")
2081
+ else:
2082
+ _ok("Dizinler ve PATH doğrulandı.")
2083
+
2084
+ apps = registry.list_apps()
2085
+ broken = 0
2086
+ for app in apps:
2087
+ app_ok = Path(app.get("app_dir", "")).is_dir()
2088
+ shims_ok = all(Path(s).exists() for s in app.get("shims", []))
2089
+ if not (app_ok and shims_ok):
2090
+ broken += 1
2091
+ _warn(f"Bozuk kurulum tespit edildi: {app['name']} (onarmak için: meu install {app['name']} --force)")
2092
+
2093
+ if broken == 0:
2094
+ _ok(f"Kayıtlı {len(apps)} uygulamanın tamamı sağlıklı.")
2095
+ return 0
2096
+
2097
+
2098
+ def cmd_self_install(args: argparse.Namespace) -> int:
2099
+ paths = get_meu_paths()
2100
+ for key in ("home", "core_dir", "apps_dir", "cache_dir", "bin_dir", "internal_bin_dir"):
2101
+ paths[key].mkdir(parents=True, exist_ok=True)
2102
+
2103
+ src_self = Path(__file__).resolve()
2104
+ dst_self = paths["core_dir"] / "meu.py"
2105
+ if src_self != dst_self.resolve():
2106
+ shutil.copy2(src_self, dst_self)
2107
+ if os.name != "nt":
2108
+ os.chmod(dst_self, 0o755)
2109
+
2110
+ cmd_spec = {"name": "meu", "target_type": "python_script", "script": "meu.py", "gui": False}
2111
+ shims = create_command_shims(
2112
+ paths["bin_dir"],
2113
+ paths["internal_bin_dir"],
2114
+ paths["core_dir"],
2115
+ cmd_spec,
2116
+ Path(sys.executable),
2117
+ )
2118
+
2119
+ path_added = _ensure_user_path(paths["bin_dir"])
2120
+ _ok(f"meu v{__version__} başarıyla kuruldu!")
2121
+ _info(f"Çekirdek : {dst_self}")
2122
+ _info(f"Komutlar : {', '.join(str(p) for p in shims)}")
2123
+ if path_added:
2124
+ _info(f"PATH eklendi ({paths['bin_dir']}). Yeni bir terminal açarak doğrudan 'meu' yazabilirsiniz.")
2125
+ elif not os.environ.get("MEU_HOME") and not _path_contains_dir(paths["bin_dir"]):
2126
+ _warn(f"'{paths['bin_dir']}' PATH içinde değil; eklemek için: meu doctor --fix")
2127
+ return 0
2128
+
2129
+
2130
+ def build_parser() -> argparse.ArgumentParser:
2131
+ parser = argparse.ArgumentParser(
2132
+ prog="meu",
2133
+ description="meu — Windows 10 ve Linux için GitHub (meucak) proje & paket yöneticisi.",
2134
+ )
2135
+ parser.add_argument("-V", "--version", action="version", version=f"meu {__version__}")
2136
+ sub = parser.add_subparsers(dest="command", metavar="KOMUT")
2137
+
2138
+ p_install = sub.add_parser(
2139
+ "install",
2140
+ aliases=["i", "add", "kur", "indir"],
2141
+ help="GitHub proje adı veya linkinden indir ve kur (örn. meu install recep)",
2142
+ )
2143
+ p_install.add_argument("targets", nargs="+", help="Proje adı (recep) veya GitHub linki")
2144
+ p_install.add_argument("-f", "--force", action="store_true", help="Mevcut kurulumun üzerine yeniden kur")
2145
+ p_install.add_argument("--no-deps", action="store_true", help="Python sanal ortam/pip kurulumunu atla")
2146
+ p_install.add_argument("--no-desktop", action="store_true", help="Masaüstü/uygulama kısayolu oluşturma")
2147
+ p_install.add_argument("-b", "--branch", default=None, help="Belirli bir Git dalı/etiketi kur")
2148
+ p_install.add_argument("--docker", action="store_true", help="Docker Compose servisi varsa kurulumda başlat")
2149
+ p_install.add_argument("--zip", action="store_true", help="Git yerine doğrudan GitHub ZIP arşivi kullan")
2150
+ p_install.set_defaults(func=cmd_install)
2151
+
2152
+ p_uninstall = sub.add_parser(
2153
+ "uninstall",
2154
+ aliases=["remove", "rm", "sil", "kaldir"],
2155
+ help="Kurulu projeyi komut ve kısayollarıyla birlikte temizce kaldır",
2156
+ )
2157
+ p_uninstall.add_argument("targets", nargs="+", help="Kaldırılacak proje adları")
2158
+ p_uninstall.set_defaults(func=cmd_uninstall)
2159
+
2160
+ p_update = sub.add_parser(
2161
+ "update",
2162
+ aliases=["upgrade", "guncelle"],
2163
+ help="Kurulu projeyi veya tüm projeleri GitHub'dan güncelle",
2164
+ )
2165
+ p_update.add_argument("targets", nargs="*", help="Güncellenecek proje adları (boşsa tümü)")
2166
+ p_update.add_argument("--all", action="store_true", help="Kurulu tüm projeleri güncelle")
2167
+ p_update.add_argument("--no-deps", action="store_true", help="Bağımlılık kurulumunu atla")
2168
+ p_update.add_argument("--no-desktop", action="store_true", help="Kısayol oluşturmayı atla")
2169
+ p_update.set_defaults(func=cmd_update)
2170
+
2171
+ p_list = sub.add_parser(
2172
+ "list",
2173
+ aliases=["ls", "liste"],
2174
+ help="Kurulu projeleri listele",
2175
+ )
2176
+ p_list.add_argument("--json", action="store_true", help="JSON biçiminde yazdır")
2177
+ p_list.set_defaults(func=cmd_list)
2178
+
2179
+ p_search = sub.add_parser(
2180
+ "search",
2181
+ aliases=["catalog", "katalog", "ara"],
2182
+ help="Mevcut meucak projelerini listele veya ara",
2183
+ )
2184
+ p_search.add_argument("query", nargs="?", default="", help="Arama kelimesi")
2185
+ p_search.add_argument("--offline", action="store_true", help="Yalnızca yerleşik kataloğu kullan")
2186
+ p_search.set_defaults(func=cmd_search)
2187
+
2188
+ p_info = sub.add_parser(
2189
+ "info",
2190
+ aliases=["show", "bilgi"],
2191
+ help="Proje hakkında ayrıntılı bilgi göster",
2192
+ )
2193
+ p_info.add_argument("target", help="Proje adı veya GitHub linki")
2194
+ p_info.set_defaults(func=cmd_info)
2195
+
2196
+ p_run = sub.add_parser(
2197
+ "run",
2198
+ aliases=["start", "exec", "calistir", "ac"],
2199
+ help="Kurulu projeyi çalıştır (kurulu değilse önce otomatik kurar)",
2200
+ )
2201
+ p_run.add_argument("target", help="Çalıştırılacak proje adı veya linki")
2202
+ p_run.add_argument("extra_args", nargs=argparse.REMAINDER, help="Uygulamaya iletilecek argümanlar")
2203
+ p_run.set_defaults(func=cmd_run)
2204
+
2205
+ p_doctor = sub.add_parser(
2206
+ "doctor",
2207
+ aliases=["check", "kontrol"],
2208
+ help="Sistem gereksinimlerini, PATH ayarını ve kurulumları denetle",
2209
+ )
2210
+ p_doctor.add_argument("--fix", action="store_true", help="Eksik dizinleri ve kullanıcı PATH ayarını onar")
2211
+ p_doctor.set_defaults(func=cmd_doctor)
2212
+
2213
+ p_self = sub.add_parser(
2214
+ "self-install",
2215
+ aliases=["setup"],
2216
+ help="meu aracının kendisini sisteme ve PATH'e kur",
2217
+ )
2218
+ p_self.set_defaults(func=cmd_self_install)
2219
+
2220
+ return parser
2221
+
2222
+
2223
+ def main(argv: list[str] | None = None) -> int:
2224
+ _configure_utf8_streams()
2225
+ parser = build_parser()
2226
+ args = parser.parse_args(argv)
2227
+ if not hasattr(args, "func"):
2228
+ parser.print_help()
2229
+ return 0
2230
+ return int(args.func(args))
2231
+
2232
+
2233
+ if __name__ == "__main__":
2234
+ raise SystemExit(main())