Commit 3d519e0
3
plików
+377
dodanych
-89
usuniętych
@@ -1,7 +1,7 @@
1 1 #!/usr/bin/env python3
2 2 """
3 3 ╔══════════════════════════════════════════════════════════════════════════════╗
4 -║ PAG - Pagan Linux Package Manager v3.3.21 ║
4 +║ PAG - Pagan Linux Package Manager v4.0.1 ║
5 5 ║ Produkcyjny menedżer pakietów – atomowy, bezpieczny, i18n ║
6 6 ╚══════════════════════════════════════════════════════════════════════════════╝
7 7
@@ -55,30 +55,169 @@ import threading, itertools
55 55 import uuid # serialNumber SBOM (CycloneDX)
56 56
57 57 # Wersja klienta – do porównania z repo.json["pag_version"] (self-update)
58 -PAG_VERSION = "3.4.0"
58 +PAG_VERSION = "4.0.1"
59 59 from urllib.error import URLError, HTTPError
60 60
61 61 # =============================================================================
62 -# ProgressBar — minimalistyczny pasek postępu (bez zewnętrznych zależności)
62 +# Pagan progress — animowany pasek „Drakkar” (własny motyw Pagan/Loki)
63 +# -----------------------------------------------------------------------------
64 +# Zamiast statycznego „█” pasek jest animowany: łódź wikingów płynie po
65 +# falującym morzu, a za nią ciągnie się smuga z wędrującym refleksem. Animacja
66 +# jest funkcją czasu, więc „płynie” nawet gdy postęp stoi w miejscu (długa
67 +# instalacja jednego pakietu, przerwa między fragmentami pobierania).
68 +#
69 +# Konfiguracja (zmienne środowiskowe):
70 +# PAG_NO_ANIM=1 – wyłącz animację (zostaje klasyczny statyczny pasek)
71 +# PAG_BAR_STYLE=<styl> – drakkar (domyślnie) | snake | classic
72 +# Poza TTY animacja jest automatycznie wyłączona (czyste logi w plikach).
63 73 # =============================================================================
64 74
65 -class ProgressBar:
66 - """Czysty Python progress bar — działa z TTY i bez."""
75 +_PAGAN_ANIM = os.environ.get("PAG_NO_ANIM", "") not in ("1", "true", "yes", "on")
76 +_PAGAN_STYLE = os.environ.get("PAG_BAR_STYLE", "drakkar").strip().lower()
77 +_DRAW_LOCK = threading.Lock() # serializacja zapisów wielu pasków
78 +
79 +# Dwie fazy fali – przesuwane w czasie dają wrażenie ruchu morza.
80 +_WAVE_PHASES = ("~_", "_~")
81 +
82 +
83 +def _classic_bar(pct: float, width: int) -> str:
84 + """Klasyczny statyczny pasek █/░ (fallback dla logów i PAG_NO_ANIM)."""
85 + filled = int(round(width * max(0.0, min(100.0, pct)) / 100.0))
86 + return "█" * filled + "░" * (width - filled)
87 +
88 +
89 +def _drakkar_bar(pct: float, width: int, t: float, filled: int) -> str:
90 + """Drakkar (łódź wikingów) płynący po falującym morzu.
91 +
92 + - przed łodzią: falujące morze (~ _ przesuwane w czasie),
93 + - dziób łodzi: » (kolumna = bieżący postęp),
94 + - za łodzią: smuga z wędrującym refleksem światła.
95 + """
96 + done = pct >= 100.0
97 + wave = _WAVE_PHASES[int(t * 6) % len(_WAVE_PHASES)]
98 + ship = min(filled, width - 1)
99 + glow = int(t * 10) % ship if ship > 0 else -1
100 + out = []
101 + for i in range(width):
102 + if done:
103 + out.append("»" if i == width - 1 else "█") # łódź zacumowana
104 + elif i < ship:
105 + out.append("█" if i == glow else "▓")
106 + elif i == ship:
107 + out.append("»")
108 + else:
109 + out.append(wave[i & 1])
110 + return "".join(out)
111 +
112 +
113 +def _snake_bar(pct: float, width: int, t: float, filled: int) -> str:
114 + """Jörmungandr – wąż sunący przez pasek (głowa @, łuski o/~, ogon ·)."""
115 + done = pct >= 100.0
116 + head = min(filled, width - 1)
117 + out = []
118 + for i in range(width):
119 + if done:
120 + out.append("@" if i == width - 1 else "o")
121 + elif i < head:
122 + out.append("o" if (i + int(t * 6)) & 1 else "~")
123 + elif i == head:
124 + out.append("@")
125 + else:
126 + out.append("·")
127 + return "".join(out)
128 +
129 +
130 +def _pagan_bar(pct: float, width: int = 30, t: float = 0.0,
131 + style: Optional[str] = None, animated: bool = True) -> str:
132 + """Zwraca jednoliniowy pasek postępu o STAŁEJ szerokości `width`.
133 +
134 + `pct` – postęp 0..100
135 + `t` – czas (s); różne `t` → inna klatka animacji
136 + `animated` – False wymusza klasyczny statyczny pasek (np. brak TTY)
137 + """
138 + width = max(6, int(width))
139 + pct = max(0.0, min(100.0, float(pct)))
140 + style = style or _PAGAN_STYLE
141 + if not animated or not _PAGAN_ANIM or style == "classic":
142 + return _classic_bar(pct, width)
143 + filled = int(round(width * pct / 100.0))
144 + if style == "snake":
145 + return _snake_bar(pct, width, t, filled)
146 + return _drakkar_bar(pct, width, t, filled)
147 +
148 +
149 +class _Bar:
150 + """Baza animowanych pasków: rysują JEDNĄ nadpisywaną linię na `stream`.
151 +
152 + Gdy mamy TTY, wątek w tle odświeża pasek ~10×/s, dzięki czemu morze faluje
153 + także wtedy, gdy postęp chwilowo się nie zmienia.
154 + """
155 + def __init__(self, width: int, stream=None):
156 + self.width = width
157 + self.stream = stream if stream is not None else sys.stderr
158 + self.tty = self.stream.isatty()
159 + self._lock = threading.RLock()
160 + self._last_len = 0
161 + self._stop = threading.Event()
162 + self._thread = None
163 +
164 + # -- wątek animacji -------------------------------------------------------
165 + def _start_anim(self):
166 + if _PAGAN_ANIM and self.tty and self._thread is None:
167 + self._thread = threading.Thread(target=self._anim_loop, daemon=True)
168 + self._thread.start()
169 +
170 + def _anim_loop(self):
171 + while not self._stop.wait(0.1):
172 + with self._lock:
173 + if self._stop.is_set():
174 + break
175 + self._write(self._line())
176 +
177 + def _stop_anim(self):
178 + self._stop.set()
179 + if self._thread is not None:
180 + self._thread.join(timeout=0.3)
181 + self._thread = None
182 +
183 + # -- rysowanie ------------------------------------------------------------
184 + def _write(self, line: str):
185 + clear = " " * max(0, self._last_len - len(line))
186 + with _DRAW_LOCK:
187 + self.stream.write(f"\r{line}{clear}")
188 + self.stream.flush()
189 + self._last_len = len(line)
190 +
191 + def _line(self) -> str:
192 + raise NotImplementedError
193 +
194 + def _clear_line(self):
195 + if self.tty and self._last_len:
196 + with _DRAW_LOCK:
197 + self.stream.write("\r" + " " * self._last_len + "\r")
198 + self.stream.flush()
199 + self._last_len = 0
200 +
201 + def _newline(self):
202 + if self.tty and self._last_len:
203 + self.stream.write("\n")
204 + self.stream.flush()
205 + self._last_len = 0
206 +
207 +
208 +class ProgressBar(_Bar):
209 + """Pasek postępu dla N elementów — animowany („drakkar”) na TTY."""
67 210 def __init__(self, total: int, desc: str = "", unit: str = "", width: int = 30):
211 + super().__init__(width)
68 212 self.total = max(total, 1)
69 213 self.desc = desc
70 214 self.unit = unit
71 - self.width = width
72 215 self.n = 0
216 + self.suffix = ""
73 217 self.start = time.time()
74 - self.tty = sys.stderr.isatty()
75 - self._last_line_len = 0
218 + self._start_anim()
76 219
77 - def update(self, n: Optional[int] = None, suffix: str = ""):
78 - if n is not None:
79 - self.n = n
80 - else:
81 - self.n += 1
220 + def _line(self) -> str:
82 221 pct = self.n / self.total * 100
83 222 elapsed = time.time() - self.start
84 223 speed = self.n / elapsed if elapsed > 0 else 0
@@ -89,23 +228,27 @@ class ProgressBar:
89 228 eta_str = f"{eta:.0f}s" if eta < 60 else f"{eta/60:.1f}m"
90 229 else:
91 230 eta_str = "?..."
92 - bar_len = int(self.width * pct / 100)
93 - bar = "█" * bar_len + "░" * (self.width - bar_len)
94 - line = f" {self.desc} [{bar}] {self.n}/{self.total} ({pct:.0f}%) ETA {eta_str}{suffix}"
95 - if self.tty:
96 - # Overwrite current line
97 - clear = " " * max(0, self._last_line_len - len(line))
98 - print(f"\r{line}{clear}", end="", file=sys.stderr, flush=True)
99 - self._last_line_len = len(line)
100 - else:
101 - # Print milestone lines only (every 10% or when done)
102 - if self.n == 1 or self.n >= self.total or self.n % max(1, self.total // 10) == 0:
103 - print(line, file=sys.stderr)
231 + bar = _pagan_bar(pct, self.width, time.time(), animated=self.tty)
232 + return f" {self.desc} [{bar}] {self.n}/{self.total} ({pct:.0f}%) ETA {eta_str}{self.suffix}"
233 +
234 + def update(self, n: Optional[int] = None, suffix: str = ""):
235 + with self._lock:
236 + if n is not None:
237 + self.n = n
238 + else:
239 + self.n += 1
240 + self.suffix = suffix
241 + if self.tty:
242 + self._write(self._line())
243 + elif (self.n == 1 or self.n >= self.total
244 + or self.n % max(1, self.total // 10) == 0):
245 + # Bez TTY – tylko kamienie milowe (czysty log)
246 + print(self._line(), file=self.stream)
104 247
105 248 def close(self):
106 - if self.tty:
107 - print(file=sys.stderr)
108 - self._last_line_len = 0
249 + self._stop_anim()
250 + with self._lock:
251 + self._newline()
109 252
110 253 def __enter__(self):
111 254 return self
@@ -114,42 +257,41 @@ class ProgressBar:
114 257 self.close()
115 258
116 259
117 -class DownloadBar:
118 - """Pasek postępu pobierania — na podstawie Content-Length."""
260 +class DownloadBar(_Bar):
261 + """Animowany pasek pobierania (na podstawie Content-Length)."""
119 262 def __init__(self, filename: str, total_bytes: int):
263 + super().__init__(25)
120 264 self.filename = filename
121 265 self.total = total_bytes
122 266 self.downloaded = 0
123 267 self.start = time.time()
124 - self.tty = sys.stderr.isatty()
125 - self._last_len = 0
268 + self._start_anim()
126 269
127 - def update(self, chunk_size: int):
128 - self.downloaded += chunk_size
129 - if self.total <= 0:
130 - return
131 - pct = self.downloaded / self.total * 100
270 + def _line(self) -> str:
271 + pct = self.downloaded / self.total * 100 if self.total > 0 else 0.0
132 272 elapsed = time.time() - self.start
133 273 speed = self.downloaded / elapsed if elapsed > 0 else 0
134 - if speed > 0:
274 + if self.total > 0 and speed > 0:
135 275 eta = (self.total - self.downloaded) / speed
136 276 eta_str = f"{eta:.0f}s" if eta < 60 else f"{eta/60:.1f}m"
137 277 else:
138 278 eta_str = "?..."
139 - bar_len = 25
140 - filled = int(bar_len * pct / 100)
141 - bar = "█" * filled + "░" * (bar_len - filled)
279 + bar = _pagan_bar(pct, self.width, time.time(), animated=self.tty)
142 280 sz = self._fmt_size(self.total)
143 281 spd = self._fmt_size(int(speed))
144 - line = f" ↓ {self.filename} [{bar}] {pct:.0f}% {sz} {spd}/s ETA {eta_str}"
145 - if self.tty:
146 - clear = " " * max(0, self._last_len - len(line))
147 - print(f"\r{line}{clear}", end="", file=sys.stderr, flush=True)
148 - self._last_len = len(line)
282 + return f" ↓ {self.filename} [{bar}] {pct:.0f}% {sz} {spd}/s ETA {eta_str}"
283 +
284 + def update(self, chunk_size: int):
285 + with self._lock:
286 + self.downloaded += chunk_size
287 + if self.tty and self.total > 0:
288 + self._write(self._line())
149 289
150 290 def close(self):
151 - if self.tty and self.total > 0:
152 - print(file=sys.stderr)
291 + self._stop_anim()
292 + with self._lock:
293 + if self.total > 0:
294 + self._newline()
153 295
154 296 @staticmethod
155 297 def _fmt_size(n: int) -> str:
@@ -159,6 +301,60 @@ class DownloadBar:
159 301 n /= 1024
160 302 return f"{n:.1f} TB"
161 303
304 +
305 +class _StepBar(_Bar):
306 + """Animowany pasek dla pętli „krok po kroku” (instalacja/aktualizacja).
307 +
308 + Pasek nie skacze skokowo co pakiet – między krokami łagodnie „dopełza”
309 + w stronę kolejnego progu (jak w instalatorach), więc rośnie w sposób
310 + ciągły. Wątek animacji odświeża go ~10×/s.
311 + """
312 + def __init__(self, total: int, icon: str = "", width: int = 25,
313 + creep_tau: float = 3.0):
314 + super().__init__(width)
315 + self.total = max(total, 1)
316 + self.icon = icon
317 + self.creep_tau = creep_tau # „stała czasu” dopełzania (s)
318 + self.idx = 0
319 + self.label = ""
320 + self.t0 = time.time()
321 + self._step_t = time.time() # start bieżącego pakietu
322 + self._start_anim()
323 +
324 + def _frac(self) -> float:
325 + """Ukończona część [0..1]: kroki + wygładzone dopełzanie w bieżącym."""
326 + done = max(0, self.idx - 1)
327 + if done >= self.total:
328 + return 1.0
329 + # 0.5 ** (dt/tau): 0 → ~1 asymptotycznie; cap 0.9, by krok był widoczny
330 + creep = 1.0 - 0.5 ** ((time.time() - self._step_t) / self.creep_tau)
331 + return (done + min(creep, 0.9)) / self.total
332 +
333 + def _line(self) -> str:
334 + pct = self._frac() * 100.0
335 + eta_s = ""
336 + if self.idx > 1:
337 + avg = (time.time() - self.t0) / (self.idx - 1)
338 + rem = avg * (self.total - self.idx + 1)
339 + eta_s = f" ~{rem:.0f}s" if rem < 60 else f" ~{rem/60:.1f}m"
340 + bar = _pagan_bar(pct, self.width, time.time(), animated=self.tty)
341 + return f" {self.icon}[{bar}] {self.idx}/{self.total} ({pct:.0f}%) {self.label}{eta_s}"
342 +
343 + def step(self, idx: int, label: str):
344 + with self._lock:
345 + self.idx = idx
346 + self.label = label
347 + self._step_t = time.time()
348 + if self.tty:
349 + self._write(self._line())
350 + else:
351 + print(self._line(), file=self.stream)
352 +
353 + def end(self):
354 + self._stop_anim()
355 + with self._lock:
356 + self._clear_line()
357 +
162 358 # =============================================================================
163 359 # GPG – BEZPIECZNE WYWOŁYWANIE (odporne na brak binarki gpg)
164 360 # =============================================================================
@@ -2887,36 +3083,17 @@ def cmd_install(package_names, as_dep=False, upgrade=False):
2887 3083 # nieinteraktywnym (logi, netinstall instalatora) wypisujemy linię na
2888 3084 # pakiet – tam to pożądane do logu.
2889 3085 t0 = time.time()
2890 - stderr_tty = sys.stderr.isatty()
2891 3086 stdout_tty = sys.stdout.isatty()
2892 - _bar_last = 0
3087 +
3088 + # Animowany pasek postępu („drakkar”) – jedna nadpisywana linia; morze
3089 + # faluje nawet wtedy, gdy pojedynczy pakiet instaluje się długo.
3090 + _pbar = _StepBar(len(to_install), icon="📦 ", width=25)
2893 3091
2894 3092 def _bar_draw(idx: int, name: str) -> None:
2895 - nonlocal _bar_last
2896 - n = len(to_install)
2897 - pct = (idx - 1) / n * 100.0
2898 - fl = int(25 * pct / 100)
2899 - pbar = "█" * fl + "░" * (25 - fl)
2900 - eta_s = ""
2901 - if idx > 1:
2902 - avg = (time.time() - t0) / (idx - 1)
2903 - rem = avg * (n - idx + 1)
2904 - eta_s = f" ~{rem:.0f}s" if rem < 60 else f" ~{rem/60:.1f}m"
2905 - line = f" 📦 [{pbar}] {idx}/{n} ({pct:.0f}%) {name}{eta_s}"
2906 - if stderr_tty:
2907 - clear = " " * max(0, _bar_last - len(line))
2908 - sys.stderr.write(f"\r{line}{clear}")
2909 - sys.stderr.flush()
2910 - _bar_last = len(line)
2911 - else:
2912 - print(line, file=sys.stderr, flush=True)
3093 + _pbar.step(idx, name)
2913 3094
2914 3095 def _bar_end() -> None:
2915 - nonlocal _bar_last
2916 - if stderr_tty and _bar_last:
2917 - sys.stderr.write("\r" + " " * _bar_last + "\r")
2918 - sys.stderr.flush()
2919 - _bar_last = 0
3096 + _pbar.end()
2920 3097
2921 3098 _pkg_i = 0
2922 3099 for name in to_install:
@@ -3109,10 +3286,10 @@ def cmd_remove(package_names):
3109 3286 if name not in installed_db:
3110 3287 print(f" ⚠ {name}: not installed"); continue
3111 3288
3112 - # Pasek postępu
3289 + # Pasek postępu (animowany „drakkar” na TTY)
3113 3290 pct = (i - 1) / total * 100
3114 - filled = int(25 * pct / 100)
3115 - print(f" 🗑 [{'█' * filled + '░' * (25 - filled)}] {i}/{total} ({pct:.0f}%) ", end="\r", file=sys.stderr, flush=True)
3291 + bar = _pagan_bar(pct, 25, time.time(), animated=sys.stderr.isatty())
3292 + print(f" 🗑 [{bar}] {i}/{total} ({pct:.0f}%) ", end="\r", file=sys.stderr, flush=True)
3116 3293
3117 3294 print(f"🗑 {name}-{installed_db[name]['version']} ...", end=" ", flush=True)
3118 3295
@@ -3451,6 +3628,10 @@ BASE_NAME_ALIASES = {
3451 3628 "xinit": "xorg-xinit",
3452 3629 "xkbcomp": "xorg-xkbcomp",
3453 3630 "xkeyboard-config": "xorg-xkeyboard-config",
3631 + # Builder buduje wpa_supplicant (z podkreślnikiem), a repo ma wpa-supplicant
3632 + # (z myślnikiem) – bez tego aliasu pakiet nie dostawał aktualizacji z repo,
3633 + # mimo że repo.json zna DOKŁADNIE tę samą wersję.
3634 + "wpa_supplicant": "wpa-supplicant",
3454 3635 }
3455 3636
3456 3637
@@ -3610,6 +3791,101 @@ def cmd_base_adopt(args):
3610 3791 return _rc
3611 3792
3612 3793
3794 +def _base_cached_index() -> dict:
3795 + """Indeks repo TYLKO z lokalnego cache (zero sieci) – do mapowania nazw.
3796 +
3797 + Potrzebne dla `pag base register`: rejestracja bazy obrazu nie może zależeć
3798 + od sieci (odpala się w buildzie, w chroocie, bez DNS). Cache indeksu powstaje
3799 + przy okazji `pag sync`/`pag install` i po nim wystarcza.
3800 + """
3801 + _out = {}
3802 + try:
3803 + for _r in get_repos():
3804 + _cp = _repo_cache_path(_r)
3805 + if not os.path.exists(_cp):
3806 + continue
3807 + for _pdata in (_load_repo_cache(_cp) or []):
3808 + _n = _pdata.get("name") or _pdata.get("filename", "?").split("-")[0]
3809 + _pkg = PackageInfo(_pdata, _r)
3810 + if _n not in _out or _version_newer(_pkg.version, _out[_n].version):
3811 + _out[_n] = _pkg
3812 + except Exception:
3813 + return _out
3814 + return _out
3815 +
3816 +
3817 +def cmd_base_register(args):
3818 + """`pag base register [--force] [--dry-run]` – wpisz bazę obrazu do installed.json.
3819 +
3820 + PO CO: pakietów zbudowanych przez builder (glibc, gcc, GTK, XFCE…) nie ma
3821 + w installed.json, więc `pag upgrade` ich NIE widzi i system nie da się
3822 + prowadzić w trybie rolling – trzeba by najpierw `pag base adopt`, czyli
3823 + ponownie ŚCIĄGNĄĆ całą bazę z repo. Rejestracja zamiast tego zapisuje je
3824 + jako zainstalowane **z wersją z obrazu** (to ona leży na dysku), więc
3825 + `pag upgrade` porówna ją z repo i podniesie tylko to, co nowsze.
3826 +
3827 + Offline: nic nie pobiera. Cache indeksu repo (jeśli jest) służy WYŁĄCZNIE do
3828 + mapowania nazw builder → repo (BASE_NAME_ALIASES/provides) i metadanych
3829 + (release/opis/zależności). Nazwy bez odpowiednika w repo zostają jak są.
3830 +
3831 + OGRANICZENIE: rejestracja nie zna listy plików pakietu (files.db), więc
3832 + dopóki pakiet nie zostanie zaktualizowany z repo, `pag verify`/`pag remove`
3833 + go nie obejmą (`pag base adopt` nadal jest drogą do pełnego przejęcia).
3834 + """
3835 + _force = "-f" in args or "--force" in args
3836 + _dry = "-n" in args or "--dry-run" in args
3837 +
3838 + _entries = _base_entries()
3839 + if not _entries:
3840 + print(f" ℹ {_('base_no_manifest')}")
3841 + return 1
3842 +
3843 + _repo = _base_cached_index()
3844 + installed = load_json(INSTALLED_DB)
3845 + world = load_world()
3846 + _now = datetime.now().isoformat()
3847 +
3848 + added, skipped, renamed = [], 0, 0
3849 + for _n, _v in _entries:
3850 + _real = _base_repo_name(_n, _repo, installed) if _repo else ""
3851 + _key = _real or _n
3852 + if _real and _real != _n:
3853 + renamed += 1
3854 + if _key in installed and not _force:
3855 + skipped += 1
3856 + continue
3857 + _pkg = _repo.get(_key)
3858 + installed[_key] = {
3859 + "version": _v or (getattr(_pkg, "version", "") or "?"),
3860 + "release": getattr(_pkg, "release", "") or "1",
3861 + "description": (getattr(_pkg, "description", "") or "")
3862 + or "Pagan Linux – pakiet bazy obrazu",
3863 + "dependencies": list(getattr(_pkg, "dependencies", []) or []),
3864 + "size_bytes": getattr(_pkg, "size_bytes", 0) or 0,
3865 + "sha256": "",
3866 + "installed_at": _now,
3867 + "repo": "base",
3868 + "provides": list(getattr(_pkg, "provides", []) or []),
3869 + "provides_so": list(getattr(_pkg, "provides_so", []) or []),
3870 + "requires_so": list(getattr(_pkg, "requires_so", []) or []),
3871 + }
3872 + world.add(_key)
3873 + added.append(_key)
3874 +
3875 + if _dry:
3876 + print(f" ℹ {_('base_register_plan', len(added))}")
3877 + return 0
3878 + if added:
3879 + save_json(INSTALLED_DB, installed)
3880 + save_world(world)
3881 + print(f" ✅ {_('base_register_ok', len(added), skipped)}")
3882 + if renamed:
3883 + print(f" ℹ {_('base_register_renamed', renamed)}")
3884 + if not _repo:
3885 + print(f" ℹ {_('base_register_nocache')}")
3886 + return 0
3887 +
3888 +
3613 3889 def cmd_update(do_upgrade: bool = False):
3614 3890 """`pag sync` / `pag update` – odświeżenie indeksów + raport aktualizacji.
3615 3891
@@ -5443,7 +5719,9 @@ def _verify_so_deps(to_install: list, repo: dict, installed: dict) -> int:
5443 5719 print()
5444 5720 return len(missing)
5445 5721
5446 -def _download_pkg(pkg, attempts: int = 3):
5722 +def _download_pkg(pkg, attempts: int = 3, progress: bool = True):
5723 + """Pobiera pakiet do cache. `progress=False` wycisza pasek (np. gdy
5724 + równoległy pobierający pokazuje własny pasek zbiorczy)."""
5447 5725 url = f"{pkg.repo_url}/{pkg.filename}"
5448 5726 dest = os.path.join(PAG_CACHE, pkg.filename)
5449 5727 if os.path.exists(dest) and (not pkg.sha256 or _sha256_file(dest) == pkg.sha256):
@@ -5455,15 +5733,17 @@ def _download_pkg(pkg, attempts: int = 3):
5455 5733 req = Request(url, headers={"User-Agent":"pag/3.0"})
5456 5734 with urlopen(req, timeout=600) as resp:
5457 5735 total = int(resp.headers.get("Content-Length", 0))
5458 - bar = DownloadBar(pkg.filename, total)
5736 + bar = DownloadBar(pkg.filename, total) if progress else None
5459 5737 with open(dest, "wb") as f:
5460 5738 while True:
5461 5739 chunk = resp.read(65536)
5462 5740 if not chunk:
5463 5741 break
5464 5742 f.write(chunk)
5465 - bar.update(len(chunk))
5466 - bar.close()
5743 + if bar is not None:
5744 + bar.update(len(chunk))
5745 + if bar is not None:
5746 + bar.close()
5467 5747 if pkg.sha256 and _sha256_file(dest) != pkg.sha256:
5468 5748 last_err = "SHA256 mismatch"
5469 5749 try:
@@ -5545,7 +5825,7 @@ def _download_packages_parallel(pkgs: List[PackageInfo], max_workers: int = 4) -
5545 5825 total = len(pkgs)
5546 5826 completed = 0
5547 5827 with ThreadPoolExecutor(max_workers=max_workers) as executor:
5548 - future_to_pkg = {executor.submit(_download_pkg, pkg): pkg for pkg in pkgs}
5828 + future_to_pkg = {executor.submit(_download_pkg, pkg, progress=False): pkg for pkg in pkgs}
5549 5829 for future in as_completed(future_to_pkg):
5550 5830 pkg = future_to_pkg[future]
5551 5831 try:
@@ -5553,10 +5833,9 @@ def _download_packages_parallel(pkgs: List[PackageInfo], max_workers: int = 4) -
5553 5833 except Exception:
5554 5834 results[pkg.name] = None
5555 5835 completed += 1
5556 - # Pasek postępu
5836 + # Pasek postępu (animowany „drakkar” na TTY)
5557 5837 pct = completed / total * 100
5558 - filled = int(20 * pct / 100)
5559 - bar = "█" * filled + "░" * (20 - filled)
5838 + bar = _pagan_bar(pct, 20, time.time(), animated=sys.stderr.isatty())
5560 5839 print(f"\r ⏬ [{bar}] {completed}/{total} ({pct:.0f}%)", end="", file=sys.stderr, flush=True)
5561 5840 print(file=sys.stderr) # nowa linia po zakończeniu
5562 5841 return results
@@ -5860,7 +6139,7 @@ def main():
5860 6139 # --- `pag base` / `pag base status`: tylko odczyt (bez roota i bez locka) ---
5861 6140 # `pag base adopt` NIE wpada tutaj – idzie ścieżką komend zapisu (roota + lock
5862 6141 # pilnuje wspólna obsługa niżej), żeby transakcja była bezpieczna.
5863 - if cmd in ("base", "base-status") and not (args and args[0] == "adopt"):
6142 + if cmd in ("base", "base-status") and not (args and args[0] in ("adopt", "register")):
5864 6143 sys.exit(cmd_base_status() or 0)
5865 6144
5866 6145 # --- Smart search: `pag <nazwa-pakietu>` → repo + Flathub + sugestie ---
@@ -5871,7 +6150,7 @@ def main():
5871 6150 "self-update",
5872 6151 "flatpak", "flatpak-install", "flatpak-remove", "flatpak-update",
5873 6152 "deploy-rollback", "deploy-cleanup", "initramfs-update", "grub-update",
5874 - "base", "base-adopt",
6153 + "base", "base-adopt", "base-register",
5875 6154 }
5876 6155 if cmd not in WRITE_CMDS:
5877 6156 # Literówka komendy? (np. `pag instal steam` zamiast `pag install`) –
@@ -5930,8 +6209,9 @@ def main():
5930 6209 "deploy-cleanup": lambda: cmd_deploy_cleanup(int(args[0]) if args else 3),
5931 6210 "initramfs-update": cmd_initramfs_update,
5932 6211 "grub-update": cmd_grub_update,
5933 - "base": lambda: cmd_base_adopt(args),
6212 + "base": lambda: cmd_base_register(args) if (args and args[0] == "register") else cmd_base_adopt(args),
5934 6213 "base-adopt": lambda: cmd_base_adopt(args),
6214 + "base-register": lambda: cmd_base_register(args),
5935 6215 }
5936 6216
5937 6217 fn = WRITE_COMMANDS.get(cmd)
@@ -15,6 +15,10 @@
15 15 "base_nothing_selected": "None of the given names is on the adopt list.",
16 16 "base_overwrite": "{} comes from the ISO image – its files will be replaced (backup kept for 'pag rollback').",
17 17 "base_reboot_hint": "Base adopted from the repo – reboot before using the new libraries/toolchain.",
18 + "base_register_nocache": "No cached repo index – builder names kept as-is (run 'sudo pag sync' and 'pag base register' again to map them to repo names).",
19 + "base_register_ok": "Registered {} base packages in the package DB ({} were already tracked).",
20 + "base_register_plan": "Dry run – would register {} base packages.",
21 + "base_register_renamed": "{} names were matched to their repo package names.",
18 22 "base_title": "Base from the ISO image",
19 23 "base_total": "Base packages (from image)",
20 24 "base_tracked": "Managed by pag",
@@ -111,7 +115,7 @@
111 115 "updated_done": "Index refresh complete. {} packages cached.",
112 116 "updates_available": "⚠ {} packages have updates – run: pag update",
113 117 "upgrading": "Upgrading: {} packages",
114 - "usage": "pag v3 – Pagan Linux Package Manager\n\nBASIC:\n pag install <pkg>... Install packages\n pag remove <pkg>... Remove packages\n pag update Update PACKAGES (refreshes indexes first)\n pag sync Refresh indexes + show pending package updates\n pag upgrade Update SYSTEM (packages + kernel/initramfs/GRUB)\n pag list [--installed] List available / installed\n pag search <query> Search packages\n pag info <pkg> Package details\n pag files <pkg> List package files\n pag verify [--deep] Verify integrity (--deep = SHA256 per file)\n pag clean Clear download cache\n pag stats System statistics\n pag download <pkg>... Download packages to cache (offline prep)\n\nROLLING (base baked into the image):\n pag base [status] Image packages vs. repo (what pag manages)\n pag base adopt [pkg...] Adopt base packages from the repo (--dry-run = preview)\n\nSECURITY:\n pag key-add <url|file> Import GPG key\n pag key-list List trusted keys\n pag key-remove <id> Remove key\n pag key-trust <repo> Pin repo signing key fingerprint (no TOFU)\n pag key-untrust <repo> Forget repo fingerprint (back to TOFU)\n pag key-trusted List pinned repo fingerprints\n\nADVANCED:\n pag why <pkg> Show why a package is installed\n pag autoremove Auto-remove orphaned dependencies\n pag pin <pkg> [ver] Pin package version\n pag unpin <pkg> Unpin\n pag pinned List pinned\n pag history Transaction history\n pag rollback Rollback last transaction\n pag remove-orphans Remove orphaned deps\n pag repo-add <url> [name] Add repository (drop-in /etc/pag/repos/)\n pag repo-list List repositories\n pag sbom export [fmt] SBOM manifest (spdx|cyclonedx)\n\nFLATPAK:\n pag flatpak [<query>] Search & install (smart)\n pag flatpak search <q> Search Flathub\n pag flatpak install <id> Install flatpak\n pag flatpak remove <id> Remove flatpak\n pag flatpak list List installed flatpaks\n pag flatpak update Update all flatpaks\n pag flatpak info <id> Show flatpak details\n\nIMMUTABLE OS (PAG_IMMUTABLE=1):\n pag deploy-list List all deployments\n pag deploy-rollback Switch to previous deployment\n pag deploy-cleanup [N] Remove old deployments (keep last N, default 3)\n pag initramfs-update Rebuild initramfs for current kernel/deployment\n pag grub-update Regenerate GRUB entries for all deployments\n",
118 + "usage": "pag v4 – Pagan Linux Package Manager\n\nBASIC:\n pag install <pkg>... Install packages\n pag remove <pkg>... Remove packages\n pag update Update PACKAGES (refreshes indexes first)\n pag sync Refresh indexes + show pending package updates\n pag upgrade Update SYSTEM (packages + kernel/initramfs/GRUB)\n pag list [--installed] List available / installed\n pag search <query> Search packages\n pag info <pkg> Package details\n pag files <pkg> List package files\n pag verify [--deep] Verify integrity (--deep = SHA256 per file)\n pag clean Clear download cache\n pag stats System statistics\n pag download <pkg>... Download packages to cache (offline prep)\n\nROLLING (base baked into the image):\n pag base [status] Image packages vs. repo (what pag manages)\n pag base adopt [pkg...] Adopt base packages from the repo (--dry-run = preview)\n\nSECURITY:\n pag key-add <url|file> Import GPG key\n pag key-list List trusted keys\n pag key-remove <id> Remove key\n pag key-trust <repo> Pin repo signing key fingerprint (no TOFU)\n pag key-untrust <repo> Forget repo fingerprint (back to TOFU)\n pag key-trusted List pinned repo fingerprints\n\nADVANCED:\n pag why <pkg> Show why a package is installed\n pag autoremove Auto-remove orphaned dependencies\n pag pin <pkg> [ver] Pin package version\n pag unpin <pkg> Unpin\n pag pinned List pinned\n pag history Transaction history\n pag rollback Rollback last transaction\n pag remove-orphans Remove orphaned deps\n pag repo-add <url> [name] Add repository (drop-in /etc/pag/repos/)\n pag repo-list List repositories\n pag sbom export [fmt] SBOM manifest (spdx|cyclonedx)\n\nFLATPAK:\n pag flatpak [<query>] Search & install (smart)\n pag flatpak search <q> Search Flathub\n pag flatpak install <id> Install flatpak\n pag flatpak remove <id> Remove flatpak\n pag flatpak list List installed flatpaks\n pag flatpak update Update all flatpaks\n pag flatpak info <id> Show flatpak details\n\nIMMUTABLE OS (PAG_IMMUTABLE=1):\n pag deploy-list List all deployments\n pag deploy-rollback Switch to previous deployment\n pag deploy-cleanup [N] Remove old deployments (keep last N, default 3)\n pag initramfs-update Rebuild initramfs for current kernel/deployment\n pag grub-update Regenerate GRUB entries for all deployments\n",
115 119 "verify_errors": "{} problems found:",
116 120 "verify_ok": "All {} files intact.",
117 121 "why_dependency": "dependency of",
@@ -15,6 +15,10 @@
15 15 "base_nothing_selected": "Żadna z podanych nazw nie jest na liście do adoptowania.",
16 16 "base_overwrite": "{} pochodzi z obrazu ISO – pliki zostaną zastąpione (kopia zapasowa dla 'pag rollback').",
17 17 "base_reboot_hint": "Baza zaadoptowana z repo – zrestartuj system, zanim zaczniesz używać nowych bibliotek/narzędzi.",
18 + "base_register_nocache": "Brak cache indeksu repo – zostawiono nazwy z buildera (uruchom 'sudo pag sync' i ponownie 'pag base register', aby je zmapować).",
19 + "base_register_ok": "Zarejestrowano {} pakietów bazy w bazie pakietów ({} już było).",
20 + "base_register_plan": "Dry-run – zarejestrowałbym {} pakietów bazy.",
21 + "base_register_renamed": "{} nazw dopasowano do nazw pakietów w repo.",
18 22 "base_title": "Baza z obrazu ISO",
19 23 "base_total": "Pakiety bazy (z obrazu)",
20 24 "base_tracked": "Zarządzane przez pag",
@@ -119,7 +123,7 @@
119 123 "updated_done": "Odświeżanie zakończone. {} pakietów w cache.",
120 124 "updates_available": "⚠ jest {} pakietów do zaktualizowania – wpisz: pag update",
121 125 "upgrading": "Aktualizacje: {} pakietów",
122 - "usage": "pag v3 – Pagan Linux Package Manager\n\nPODSTAWOWE:\n pag install <pkg>... Instalacja pakietów\n pag remove <pkg>... Usuwanie pakietów\n pag update Aktualizacja PAKIETÓW (odświeża indeksy)\n pag sync Odśwież indeksy + info o aktualizacjach\n pag upgrade Aktualizacja SYSTEMU (pakiety + kernel/initramfs/GRUB)\n pag list [--installed] Lista dostępnych / zainstalowanych\n pag search <query> Szukaj pakietów\n pag info <pkg> Szczegóły pakietu\n pag files <pkg> Lista plików pakietu\n pag verify [--deep] Weryfikacja integralności\n pag clean Wyczyść cache pobierania\n pag stats Statystyki systemu\n pag download <pkg>... Pobierz do cache (offline)\n\nROLLING (baza wypalona w obrazie):\n pag base [status] Pakiety z obrazu vs repo (czym pag zarządza)\n pag base adopt [pkg...] Adoptuj pakiety bazy z repo (--dry-run = podgląd)\n\nBEZPIECZEŃSTWO:\n pag key-add <url|file> Importuj klucz GPG\n pag key-list Lista zaufanych kluczy\n pag key-remove <id> Usuń klucz\n pag key-trust <repo> Przypnij fingerprint klucza repo (bez TOFU)\n pag key-untrust <repo> Zapomnij fingerprint repo (powrót do TOFU)\n pag key-trusted Lista przypiętych fingerprintów repo\n\nZAAWANSOWANE:\n pag why <pkg> Dlaczego pakiet jest zainstalowany\n pag autoremove Usuń osierocone zależności\n pag pin <pkg> [ver] Przypnij wersję pakietu\n pag unpin <pkg> Odepnij\n pag pinned Lista przypiętych\n pag history Historia transakcji\n pag rollback Cofnij ostatnią transakcję\n pag remove-orphans Usuń osierocone zależności\n pag repo-add <url> [nazwa] Dodaj repozytorium (drop-in w /etc/pag/repos/)\n pag repo-list Lista repozytoriów\n pag sbom export [fmt] Manifest SBOM (spdx|cyclonedx)\n\nFLATPAK:\n pag flatpak [<query>] Szukaj i instaluj\n pag flatpak search <q> Szukaj na Flathub\n pag flatpak install <id> Zainstaluj flatpak\n pag flatpak remove <id> Usuń flatpak\n pag flatpak list Lista zainstalowanych\n pag flatpak update Aktualizuj wszystkie\n pag flatpak info <id> Szczegóły flatpaka\n\nIMMUTABLE OS (PAG_IMMUTABLE=1):\n pag deploy-list Lista wdrożeń\n pag deploy-rollback Przełącz na poprzednie wdrożenie\n pag deploy-cleanup [N] Usuń stare wdrożenia (zachowaj N, domyślnie 3)\n pag initramfs-update Przebuduj initramfs\n pag grub-update Regeneruj wpisy GRUB",
126 + "usage": "pag v4 – Pagan Linux Package Manager\n\nPODSTAWOWE:\n pag install <pkg>... Instalacja pakietów\n pag remove <pkg>... Usuwanie pakietów\n pag update Aktualizacja PAKIETÓW (odświeża indeksy)\n pag sync Odśwież indeksy + info o aktualizacjach\n pag upgrade Aktualizacja SYSTEMU (pakiety + kernel/initramfs/GRUB)\n pag list [--installed] Lista dostępnych / zainstalowanych\n pag search <query> Szukaj pakietów\n pag info <pkg> Szczegóły pakietu\n pag files <pkg> Lista plików pakietu\n pag verify [--deep] Weryfikacja integralności\n pag clean Wyczyść cache pobierania\n pag stats Statystyki systemu\n pag download <pkg>... Pobierz do cache (offline)\n\nROLLING (baza wypalona w obrazie):\n pag base [status] Pakiety z obrazu vs repo (czym pag zarządza)\n pag base adopt [pkg...] Adoptuj pakiety bazy z repo (--dry-run = podgląd)\n\nBEZPIECZEŃSTWO:\n pag key-add <url|file> Importuj klucz GPG\n pag key-list Lista zaufanych kluczy\n pag key-remove <id> Usuń klucz\n pag key-trust <repo> Przypnij fingerprint klucza repo (bez TOFU)\n pag key-untrust <repo> Zapomnij fingerprint repo (powrót do TOFU)\n pag key-trusted Lista przypiętych fingerprintów repo\n\nZAAWANSOWANE:\n pag why <pkg> Dlaczego pakiet jest zainstalowany\n pag autoremove Usuń osierocone zależności\n pag pin <pkg> [ver] Przypnij wersję pakietu\n pag unpin <pkg> Odepnij\n pag pinned Lista przypiętych\n pag history Historia transakcji\n pag rollback Cofnij ostatnią transakcję\n pag remove-orphans Usuń osierocone zależności\n pag repo-add <url> [nazwa] Dodaj repozytorium (drop-in w /etc/pag/repos/)\n pag repo-list Lista repozytoriów\n pag sbom export [fmt] Manifest SBOM (spdx|cyclonedx)\n\nFLATPAK:\n pag flatpak [<query>] Szukaj i instaluj\n pag flatpak search <q> Szukaj na Flathub\n pag flatpak install <id> Zainstaluj flatpak\n pag flatpak remove <id> Usuń flatpak\n pag flatpak list Lista zainstalowanych\n pag flatpak update Aktualizuj wszystkie\n pag flatpak info <id> Szczegóły flatpaka\n\nIMMUTABLE OS (PAG_IMMUTABLE=1):\n pag deploy-list Lista wdrożeń\n pag deploy-rollback Przełącz na poprzednie wdrożenie\n pag deploy-cleanup [N] Usuń stare wdrożenia (zachowaj N, domyślnie 3)\n pag initramfs-update Przebuduj initramfs\n pag grub-update Regeneruj wpisy GRUB",
123 127 "verify_errors": "Znaleziono {} problemów:",
124 128 "verify_ok": "Wszystkie {} plików sprawne.",
125 129 "why_dependency": "zależność od",