-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbetter-pkg
More file actions
5700 lines (5088 loc) · 244 KB
/
better-pkg
File metadata and controls
5700 lines (5088 loc) · 244 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import os
import sys
import sys
import subprocess
import argparse
import re
import shutil
import signal
import json
import requests
import datetime
import importlib.util
from time import sleep
from typing import List, Tuple
from concurrent.futures import ThreadPoolExecutor
#handler for ctrl+c
def signal_handler(sig, frame):
print('\nScript was interrupted. \n⚠️ If you interrupted the script during update/installation process, clean up your system (using cleanup command) and remove cache (using cache command)! ⚠️')
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
try:
subprocess.run(["dbus-launch"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
except subprocess.CalledProcessError:
pass
class Colors:
def __init__(self):
self.use_color = "NO_COLOR" not in os.environ
if self.use_color:
self.NC = '\033[0m'
self.BGreen = '\033[1;32m'
self.BCyan = '\033[1;36m'
self.BYellow = '\033[1;33m'
self.BPurple = '\033[1;35m'
self.BRed = '\033[1;31m'
self.BWhite = '\033[1;37m'
self.c1 = '\u001b[38;5;104m' # light purple
self.c2 = '\u001b[0m' # white/reset
self.c3 = '\u001b[38;5;55m' # dark purple
self.c4 = '\u001b[38;5;98m' # medium purple
else:
self.NC = self.BGreen = self.BCyan = self.BYellow = ''
self.BPurple = self.BRed = self.BWhite = ''
self.c1 = self.c2 = self.c3 = self.c4 = ''
def print_status(message, status="info"):
"""Barevný výpis stavových zpráv"""
colors = Colors()
if status == "info":
print(f"{colors.BCyan}ℹ {message}{colors.NC}")
elif status == "success":
print(f"{colors.BGreen}✓ {message}{colors.NC}")
elif status == "warning":
print(f"{colors.BYellow}⚠ {message}{colors.NC}")
elif status == "error":
print(f"{colors.BRed}✗ {message}{colors.NC}")
# podpora pluginů
HOOKS = {
"update-plugin": [],
"upgrade-plugin": [],
"cleanup-plugin": [],
}
PACKAGE_GROUPS_EXTENSIONS = []
SETUP_FUNCTIONS = {}
CUSTOM_JSON_HANDLERS = {}
PLUGIN_COMMANDS = []
def load_plugins(command_handlers, hooks, setup_functions=None, package_groups_extensions=None, custom_json_handlers=None):
plugins_dir = os.path.expanduser("~/.local/share/better-tools/plugins/")
if not os.path.isdir(plugins_dir):
return
for fname in os.listdir(plugins_dir):
if fname.endswith(".py") and not fname.startswith("_"):
plugin_path = os.path.join(plugins_dir, fname)
modname = f"plugin_{fname[:-3]}"
try:
spec = importlib.util.spec_from_file_location(modname, plugin_path)
if spec and spec.loader:
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
if hasattr(mod, "register"):
# Vždy předávej všechny argumenty ve správném pořadí
mod.register(
command_handlers,
hooks,
setup_functions,
package_groups_extensions,
custom_json_handlers
)
except Exception as e:
print(f"Failed to load plugin {fname}: {e}")
def convert_shortcut(args_list):
"""Převádí zkrácené příkazy na dlouhé a rozkládá kombinované přepínače"""
shortcut_map = {
'-S': 'install',
'-R': 'remove',
'-L': 'list',
'-Q': 'package',
'-D': 'discover',
'-F': 'search',
'-U': 'update',
'-G': 'upgrade',
'-C': 'cleanup',
'-Y': 'repair',
'-K': 'cache',
'-J': 'setup',
'-Jc': 'setup-custom',
'-Je': 'setup-export',
'-Jr': 'setup-remove',
'-X': 'check',
'-O': 'history',
'-V': 'version'
}
converted = []
i = 0
while i < len(args_list):
arg = args_list[i]
# Převod zkrácených příkazů
if arg in shortcut_map:
converted.append(shortcut_map[arg])
i += 1
# Rozklad kombinovaných přepínačů (-Syu → install -y -u)
elif arg.startswith('-') and len(arg) > 2 and not arg.startswith('--'):
# První znak je příkaz
if f'-{arg[1]}' in shortcut_map:
converted.append(shortcut_map[f'-{arg[1]}'])
# Zbylé znaky jsou přepínače
for char in arg[2:]:
converted.append(f'-{char}')
i += 1
else:
converted.append(arg)
i += 1
return converted
def setup_argparse():
parser = argparse.ArgumentParser(
description='An universal package manager wrapper.',
add_help=True
)
# Přidání subparseru pro příkazy
subparsers = parser.add_subparsers(dest='command', help='Commands')
# Install command
install_parser = subparsers.add_parser('install', help='Install package(s)')
install_parser.add_argument('-j', '--json', action='store_true', help='Output as JSON')
install_parser.add_argument('-f', '--first', action='store_true', help='Automatically install the first package')
install_parser.add_argument('-d', '--description', action='store_true', help='Search in package descriptions')
install_parser.add_argument('-g', '--fetch', action='store_true', help='Fetch package from official source.')
install_parser.add_argument('-c', '--plugin', action='store_true', help='Install better-pkg plugin.')
install_parser.add_argument('-s', '--sclassic', action='store_true', help='Use snap --classic.')
install_parser.add_argument('-k', '--bcask', action='store_true', help='Use brew --cask.')
install_parser.add_argument('-b', '--file', action='store_true', help='Install package from file.')
install_parser.add_argument('-y', action='store_true', help='Automatic yas to prompts.')
install_parser.add_argument('-m', '--manager', choices=['apt', 'dnf', 'pacman', 'yay', 'paru', 'flatpak', 'snap', 'brew', 'pacstall', 'zypper', 'betterpkg'], help='Force install from specific package manager')
install_parser.add_argument('package', nargs='+', help='Package(s) to install')
# Remove command
remove_parser = subparsers.add_parser('remove', help='Remove package(s)')
remove_parser.add_argument('-j', '--json', action='store_true', help='Output as JSON')
remove_parser.add_argument('-f', '--first', action='store_true', help='Automatically install the first package')
remove_parser.add_argument('-d', '--description', action='store_true', help='Search in package descriptions')
remove_parser.add_argument('-c', '--plugin', action='store_true', help='Remove better-pkg plugin.')
remove_parser.add_argument('-p', '--purge', action='store_true', help='Delete package with data.')
remove_parser.add_argument('-k', '--bcask', action='store_true', help='Use brew --cask.')
remove_parser.add_argument('-m', '--manager', choices=['apt', 'dnf', 'pacman', 'yay', 'paru', 'flatpak', 'snap', 'brew', 'pacstall', 'zypper', 'betterpkg', 'appimage'], help='Force remove from specific package manager')
remove_parser.add_argument('package', nargs='+', help='Package(s) to remove')
remove_parser.add_argument('-y', action='store_true', help='Automatic yas to prompts.')
# Search command
search_parser = subparsers.add_parser('search', help='Search for package(s)')
search_parser.add_argument('-j', '--json', action='store_true', help='Output as JSON')
search_parser.add_argument('-d', '--description', action='store_true', help='Search in package descriptions')
search_parser.add_argument('package', nargs='+', help='Package(s) to search for')
# Update command
update_parser = subparsers.add_parser('update', help='Just update packages from package manager.')
update_parser.add_argument('-y', action='store_true', help='Automatic yes to prompts')
# Upgrade command
upgrade_parser = subparsers.add_parser('upgrade', help='Upgrade all packages, extensions, themes and more.')
upgrade_parser.add_argument('-s', '--skip-pre-upgrade', action='store_true', help='Skip pre-upgrade actions (not user defined).')
upgrade_parser.add_argument('-n', '--use-native', action='store_true', help='Use native way to upgrade (e.g. instead of Garuda update use pacman).')
upgrade_parser.add_argument('-m', '--skip-mirrors', action='store_true', help='Skip refreshing mirrorlist.')
upgrade_parser.add_argument('-f', '--skip-firmware', action='store_true', help='Skip upgrading firmware.')
upgrade_parser.add_argument('-d', '--distro', action='store_true', help='Upgrade whole distro to next release if avaible.')
upgrade_parser.add_argument('-b', '--unreleased', action='store_true', help='Upgrade whole distro to next unreleased (beta, alpha, dev) release if avaible.')
upgrade_parser.add_argument('-y', action='store_true', help='Automatic yes to prompts')
# Cleanup command
cleanup_parser = subparsers.add_parser('cleanup', help='Remove unused packages')
cleanup_parser.add_argument('-y', action='store_true', help='Automatic yes to prompts')
# History command
history_parser = subparsers.add_parser('history', help='Show history of actions')
history_parser.add_argument('-u', '--user', action='store_true', help='Show only user actions (install, remove)')
history_parser.add_argument('-j', '--json', action='store_true', help='Output as JSON')
history_parser.add_argument('-c', '--clear', action='store_true', help='Clear history')
# Repair command
repair_parser = subparsers.add_parser('repair', help='Try to repair broken packages')
repair_parser.add_argument('-y', action='store_true', help='Automatic yes to prompts')
# List command
list_parser = subparsers.add_parser('list', help='List installed packages')
list_parser.add_argument('-j', '--json', action='store_true', help='Output as JSON')
list_parser.add_argument('-u', '--user', action='store_true', help='List only user-installed packages')
list_parser.add_argument('-o', '--outdated', action='store_true', help='List outdated packages')
list_parser.add_argument('-n', '--unused', action='store_true', help='List unused packages')
list_parser.add_argument('-c', '--plugin', action='store_true', help='List installed better-pkg plugins')
list_parser.add_argument('-r', '--repo', nargs='+', help='List all packages from the repository (working only with system package managers and not with pacman')
# Setup command
setup_parser = subparsers.add_parser('setup', help='Setup your system. Install codecs, games, and more')
setup_parser.add_argument('-y', action='store_true', help='Automatic yes to prompts')
setup_parser.add_argument('setup', nargs='+', help='Choose what to setup.')
setup_parser.add_argument('--list-options', action='store_true', help='List available setup options')
# Setup-custom command
setup_custom_parser = subparsers.add_parser('setup-custom', help='Install and setup packages from your own configuration file')
setup_custom_parser.add_argument('config_file', help='Path to the configuration file')
setup_custom_parser.add_argument('-y', action='store_true', help='Automatic yes to prompts')
# Setup-remove command
setup_remove_parser = subparsers.add_parser('setup-remove', help='Remove packages from your own configuration file')
setup_remove_parser.add_argument('config_file', help='Path to the configuration file')
setup_remove_parser.add_argument('-y', action='store_true', help='Automatic yes to prompts')
#Cache commands
cache_parser = subparsers.add_parser('cache', help='Remove package cache')
cache_parser.add_argument('-y', action='store_true', help='Automatic yes to prompts')
#Run commands
run_parser = subparsers.add_parser('run', help='Run an application')
run_parser.add_argument('app', nargs='+', help='Application to run')
#Discover commands
discover_parser = subparsers.add_parser('discover', help='Discover new packages')
# Repo command group
repo_parser = subparsers.add_parser('repo', help='Manage repositories')
repo_subparsers = repo_parser.add_subparsers(dest='repo_command', help='Repository actions')
# repo add
repo_add = repo_subparsers.add_parser('add', help='Add a repository')
repo_add.add_argument('repo', nargs='?', help='Repository to add')
repo_add.add_argument('-c', '--choose', action='store_true', help='Choose repository from recommended list')
repo_add.add_argument('-m', '--manager', choices=['apt', 'dnf', 'pacman', 'zypper', 'flatpak', 'brew'], help='Force add to specific package manager')
# repo remove
repo_remove = repo_subparsers.add_parser('remove', help='Remove a repository')
repo_remove.add_argument('repo', nargs='?', help='Repository to remove')
repo_remove.add_argument('-c', '--choose', action='store_true', help='Choose repository from installed list')
repo_remove.add_argument('-u', '--user', action='store_true', help='Only enabled user repositories')
repo_remove.add_argument('-j', '--json', action='store_true', help='Output as JSON')
repo_remove.add_argument('-m', '--manager', choices=['apt', 'dnf', 'pacman', 'zypper', 'flatpak', 'brew'], help='Force remove from specific package manager')
# repo list
repo_list = repo_subparsers.add_parser('list', help='List configured repositories')
repo_list.add_argument('-u', '--user', action='store_true', help='Only enabled user repositories')
repo_list.add_argument('-j', '--json', action='store_true', help='Output as JSON')
repo_list.add_argument('-m', '--manager', choices=['apt', 'dnf', 'pacman', 'zypper', 'flatpak', 'brew'], help='List repos for specific package manager')
#Check commands
check_parser = subparsers.add_parser('check', help='Check (and refresh) packages, services and repositories')
check_parser.add_argument('check', nargs='+', help='Choose what to check.')
check_parser.add_argument('-j', '--json', action='store_true', help='Output as JSON')
check_parser.add_argument('-y', action='store_true', help='Automatic yes to prompts')
# Setup-export command
setup_export_parser = subparsers.add_parser('setup-export', help='Export package list to configuration file.')
setup_export_parser.add_argument('package', nargs='+', help='Package(s) to export. Type c-all to export all packages and c-category to export packages from a specific category.')
# Package command
package_parser = subparsers.add_parser('package', help='Manage and view info about package.')
package_parser.add_argument('-i', '--info', action='store_true', help='Display information about package')
package_parser.add_argument('-s', '--status', action='store_true', help='Check package status')
package_parser.add_argument('-u', '--update', action='store_true', help='Check if update is available')
package_parser.add_argument('-c', '--hold', action='store_true', help='Hold package')
package_parser.add_argument('-n', '--unhold', action='store_true', help='Unhold package')
package_parser.add_argument('-r', '--repo', action='store_true', help='Show from which repository the package is installed')
package_parser.add_argument('package', help='Package name')
selfupd_parser = subparsers.add_parser('self-update', help='Update better-pkg itself.')
selfupd_parser.add_argument('-b', '--unreleased', action='store_true', help='Update to unreleased (beta, alpha, dev) version if available.')
version_parser = subparsers.add_parser('version', help='Show version.')
# Plugin command
for name, func, help_text in PLUGIN_COMMANDS:
subparsers.add_parser(name, help=help_text)
return parser
# definice vyhledávání
def msg(*args):
input_text = " ".join(args)
print(input_text)
def prompt(input_text, index):
print(f"{input_text} [0-{index}]: \033[97m", end="")
def search_pacstall(*args, description=None):
command = ['pacstall', '-S', *args]
if description:
command[1] = '-Sd' # Hledání i v popisech
try:
result = subprocess.run(command, capture_output=True, text=True)
if result.returncode != 0:
return None
contents = []
for line in re.sub(r'\x1B\[[0-9;]*[A-Za-z]', '', result.stdout).splitlines():
if line and not line.startswith(' '): # Přeskočit prázdné řádky a popis
pkg_name = line.split()[0]
contents.append(pkg_name)
return contents if contents else None
except subprocess.CalledProcessError:
return None
def search_apt(*args, description=None):
if description:
command = ['apt', 'search', *args]
else:
command = ['apt', 'search', '--names-only', *args]
try:
env = os.environ.copy()
env['LANG'] = 'C' # Zajistí konzistentní výstup bez lokalizace
result = subprocess.run(command, capture_output=True, text=True, env=env)
contents = []
for line in result.stdout.splitlines():
if line.startswith('Sorting...') or line.startswith('Full Text Search...') or not line:
continue
if line.startswith('/'): # Přeskočí řádky začínající /
continue
parts = line.split('/', 1) # Rozdělí na název a zbytek
if len(parts) >= 1:
pkg_name = parts[0].strip()
if pkg_name and pkg_name not in contents:
contents.append(pkg_name)
return contents if contents else None
except subprocess.CalledProcessError:
return None
def search_dnf(*args, description=None):
command = ['dnf', 'search']
if description:
command.append('--all')
command.extend(args)
if shutil.which('bootc') or shutil.which('rpm-ostree'):
return None # DNF není podporován v těchto systémech
try:
result = subprocess.run(command, capture_output=True, text=True)
if result.returncode != 0:
return None
contents = []
for line in result.stdout.splitlines():
if line and not line.startswith('Last metadata') and not line.startswith('='): # Přeskočit metadata a oddělovače
# Extrahuje název balíčku před první mezerou nebo dvojtečkou
pkg_name = line.split()[0].split('.')[0]
if pkg_name and pkg_name not in contents:
contents.append(pkg_name)
return contents if contents else None
except subprocess.CalledProcessError:
return None
def search_flatpak(*args, description=None):
command = ['flatpak', 'search', '--columns=application', *args]
if description:
command = ['flatpak', 'search', *args] # Při description=True hledáme i v popisech
try:
result = subprocess.run(command, capture_output=True, text=True)
if result.returncode != 0:
return None
lines = result.stdout.splitlines()
if len(lines) <= 1: # Jen hlavička nebo prázdný výstup
return None
# Vrátit seznam aplikací bez hlavičky
contents = []
for line in lines[1:]: # Přeskočit hlavičku
if line.strip():
pkg_name = line.split()[0]
contents.append(pkg_name)
return contents if contents else None
except subprocess.CalledProcessError:
return None
def search_snap(*args, description=None):
command = ['snap', 'find', *args]
if not description:
command.extend(['--section', 'name']) # Hledat pouze v názvech
try:
result = subprocess.run(command, capture_output=True, text=True)
if result.returncode != 0:
return None
contents = []
for line in result.stdout.splitlines()[1:]: # Přeskočit hlavičku
if line.strip():
pkg_name = line.split()[0]
contents.append(pkg_name)
return contents if contents else None
except subprocess.CalledProcessError:
return None
def search_pacman(*args, description=None):
command = ['pacman', '-Ss', *args] # Vždy používáme -Ss, protože -Fs hledá v souborech
try:
result = subprocess.run(command, capture_output=True, text=True)
if result.returncode != 0:
return None
packages = []
for line in result.stdout.splitlines():
if line.startswith(' '): # Přeskočit řádky s popisem
continue
if '/' in line: # Řádky s názvy balíčků obsahují '/'
pkg_name = line.split('/')[1].split(' ')[0]
# Pokud nehledáme v popisech, kontrolujeme, zda se hledaný výraz nachází v názvu
if not description:
search_term = args[0].lower()
if search_term in pkg_name.lower():
packages.append(pkg_name)
else:
packages.append(pkg_name)
return packages if packages else None
except subprocess.CalledProcessError:
return None
def search_zypper(*args, description=False):
command = ['zypper', 'search']
if description:
command.append('-d') # Hledání i v popisech
command.extend(args)
try:
result = subprocess.run(command, capture_output=True, text=True)
if result.returncode != 0:
return None
contents = []
for line in re.sub(r'\x1B\[[0-9;]*[A-Za-z]', '', result.stdout).splitlines():
if line and not line.startswith(" ") and not line.startswith("---"):
columns = line.split('|')
if len(columns) > 1:
pkg_name = columns[1].strip() # Název balíčku je ve druhém sloupci
contents.append(pkg_name)
return contents if contents else None
except subprocess.CalledProcessError:
return None
def search_yay(*args, description=None):
command = ['yay', '-Ssa', *args] # Vždy používáme -Ss, protože -Fs hledá v souborech
try:
result = subprocess.run(command, capture_output=True, text=True)
if result.returncode != 0:
return None
packages = []
for line in result.stdout.splitlines():
if line.startswith(' '): # Přeskočit řádky s popisem
continue
if '/' in line: # Řádky s názvy balíčků obsahují '/'
pkg_name = line.split('/')[1].split(' ')[0]
# Pokud nehledáme v popisech, kontrolujeme, zda se hledaný výraz nachází v názvu
if not description:
search_term = args[0].lower()
if search_term in pkg_name.lower():
packages.append(pkg_name)
else:
packages.append(pkg_name)
return packages if packages else None
except subprocess.CalledProcessError:
return None
def search_paru(*args, description=None):
command = ['paru', '-Ssa', *args] # Přidání -A pro hledání pouze v AUR
try:
result = subprocess.run(command, capture_output=True, text=True)
if result.returncode != 0:
return None
packages = []
for line in result.stdout.splitlines():
if line.startswith(' '): # Přeskočit řádky s popisem
continue
if '/' in line: # Řádky s názvy balíčků obsahují '/'
pkg_name = line.split('/')[1].split(' ')[0]
# Pokud nehledáme v popisech, kontrolujeme, zda se hledaný výraz nachází v názvu
if not description:
search_term = args[0].lower()
if search_term in pkg_name.lower():
packages.append(pkg_name)
else:
packages.append(pkg_name)
return packages if packages else None
except subprocess.CalledProcessError:
return None
def search_brew(*args, description=None):
"""Vyhledá balíčky v Homebrew."""
command = ['brew', 'search', *args] # Odstraníme --name, protože nefunguje
try:
env = os.environ.copy()
env['PATH'] = f"/home/linuxbrew/.linuxbrew/bin:{env['PATH']}"
result = subprocess.run(command, capture_output=True, text=True, env=env)
if result.returncode != 0:
return None
packages = []
search_term = args[0].lower()
for line in result.stdout.splitlines():
if line.strip() and not line.startswith('==>'):
pkg_name = line.strip()
# Pokud nehledáme v popisech, kontrolujeme, zda se hledaný výraz nachází v názvu
if not description:
if search_term in pkg_name.lower():
packages.append(pkg_name)
else:
packages.append(pkg_name)
return packages if packages else None
except subprocess.CalledProcessError:
return None
def search_betterpkg(*args, description=None):
"""
Vyhledá balíčky v verified_urls.json (Better-pkg "repo").
"""
url = "https://raw.githubusercontent.com/ExistingPerson08/Better-pkg-data/main/verified_urls.json"
if shutil.which("apt") or shutil.which("dnf") and not shutil.which("rpm-ostree") or shutil.which("zypper"):
try:
resp = requests.get(url, timeout=5)
if resp.status_code != 200:
return None
data = resp.json()
except Exception:
return None
if not args or not args[0]:
return None
search_term = args[0].lower()
packages = []
for pkg_name in data.keys():
if not description:
if search_term in pkg_name.lower():
packages.append(pkg_name)
else:
packages.append(pkg_name)
return packages if packages else None
else:
return None # Better-pkg není podporován v těchto systémech
# definice configu
# Cesta k souboru s aliasy a příkazy před/po aktualizaci
CONFIG_PATH = os.path.expanduser("~/.config/better-tools/pkg.json")
# Výchozí aliasy
ALIASES = {
"@a-browsers": ["brave", "firefox", "chrome", "chromium", "vivaldi", "opera"],
"@a-editors": ["vim", "nano", "emacs", "code", "zed", "sublime-text"],
"@a-office": ["libreoffice", "onlyoffice", "calligra-suite", "openoffice"],
"@a-media": ["vlc", "mpv", "gimp", "audacity", "inkscape", "shotcut", "obs-studio", "kdenlive"],
"@a-graphics": ["gimp", "inkscape", "blender", "krita", "darktable"],
"@a-development": ["git", "docker", "vscode", "atom", "intellij-idea", "pycharm", "eclipse"],
"@a-system-tools": ["htop", "fastfetch", "nmap", "net-tools", "curl", "wget"],
"@a-security": ["ufw", "fail2ban", "clamav", "nmap", "gnupg"],
"@a-networking": ["openvpn", "tor", "wireguard", "curl", "nmap"],
"@a-cloud": ["docker", "kubectl", "terraform", "minikube", "ansible"],
"@a-gaming": ["steam", "lutris", "discord", "epic-games", "bottles"],
"@a-gaming-tools": ["goverlay", "mangohud", "piper", "corectrl", "obs-studio", "winetricks"],
"@a-fonts": ["font-awesome", "noto-fonts", "ttf-dejavu", "ttf-ms-fonts"],
"@a-utilities": ["htop", "fastfetch", "tree", "jq", "vim", "tmux", "wget"],
# Alias pro desktopová prostředí
"@a-de-gnome": ["gnome-shell", "gnome-tweaks", "gnome-terminal", "nautilus", "gdm"],
"@a-de-kde": ["plasma-desktop", "kde-applications", "konsole", "dolphin", "sddm"],
"@a-de-xfce": ["xfce4", "xfce4-goodies", "thunar", "xfce4-terminal", "lightdm", "lightdm-gtk-greeter"],
"@a-de-lxde": ["lxde", "pcmanfm", "lxterminal", "openbox", "lightdm"],
"@a-de-lxqt": ["lxqt", "lxqt-panel", "pcmanfm-qt", "qterminal", "sddm"],
"@a-de-mate": ["mate", "mate-extra", "caja", "mate-terminal", "lightdm", "lightdm-gtk-greeter"],
"@a-de-cinnamon": ["cinnamon", "nemo", "cinnamon-control-center", "cinnamon-settings-daemon", "lightdm", "touchegg"],
"@a-de-budgie": ["budgie-desktop", "budgie-extras", "nautilus", "lightdm"],
"@a-de-deepin": ["deepin", "deepin-extra", "deepin-terminal", "lightdm"],
"@a-wm-i3": ["i3", "i3status", "i3lock", "dmenu", "rofi", "alacritty"],
"@a-wm-sway": ["sway", "swaylock", "swayidle", "waybar", "foot"],
"@a-wm-awesome": ["awesome", "lxappearance", "rofi", "alacritty"],
"@a-wm-bspwm": ["bspwm", "sxhkd", "rofi", "alacritty"],
"@a-wm-hyprland": ["hyprland", "waybar", "swaylock", "alacritty"]
}
# Výchozí aliasy a příkazy
CONFIG_DEFAULT = {
"aliases": {
"@a-my-fav": ["firefox", "ghostty", "nautilus"]
},
"history": "true",
"pre_update_commands": [],
"post_update_commands": [],
"pre_upgrade_commands": [],
"post_upgrade_commands": [],
}
def load_config():
"""Načte konfiguraci ze souboru, pokud existuje, nebo vytvoří výchozí."""
if os.path.exists(CONFIG_PATH):
try:
with open(CONFIG_PATH, 'r', encoding='utf-8') as file:
return json.load(file)
except (json.JSONDecodeError, IOError):
print("Chyba při načítání konfigurace, vrací výchozí.")
else:
# Pokud soubor neexistuje, vytvoří se s výchozí konfigurací
save_config(CONFIG_DEFAULT)
return CONFIG_DEFAULT
def save_config(config):
"""Uloží konfiguraci do souboru."""
os.makedirs(os.path.dirname(CONFIG_PATH), exist_ok=True)
try:
with open(CONFIG_PATH, 'w', encoding='utf-8') as file:
json.dump(config, file, indent=4)
print(f"Konfigurace byla uložena do: {CONFIG_PATH}")
except IOError as e:
print(f"Chyba při ukládání konfigurace: {e}")
config = load_config()
history = config["history"]
PRE_UPDATE_COMMANDS = config["pre_update_commands"]
POST_UPDATE_COMMANDS = config["post_update_commands"]
PRE_UPGRADE_COMMANDS = config["pre_upgrade_commands"]
POST_UPGRADE_COMMANDS = config["post_upgrade_commands"]
file_aliases = config["aliases"]
ALIASES.update(file_aliases)
def resolve_aliases(packages):
"""Rozšíří aliasy v seznamu balíčků na skutečné názvy balíčků."""
resolved = set()
for pkg in packages:
if pkg in ALIASES:
resolved.update(ALIASES[pkg])
else:
resolved.add(pkg)
return list(resolved)
# Načtení historie
HISTORY_PATH = os.path.expanduser("~/.local/share/better-tools/history.jsonl")
def log_history(action, package, manager):
"""Zapíše akci do historie."""
if history == "true":
os.makedirs(os.path.dirname(HISTORY_PATH), exist_ok=True)
entry = {
"action": action, # "install" nebo "remove"
"package": package,
"manager": manager,
"datetime": datetime.datetime.now().isoformat()
}
with open(HISTORY_PATH, "a", encoding="utf-8") as f:
f.write(json.dumps(entry, ensure_ascii=False) + "\n")
# další definice
def run_command(command):
try:
subprocess.run(command, shell=True, check=True)
except subprocess.CalledProcessError:
pass
def install_package(pkgs, repo):
"""Instaluje balíčky podle správce balíčků."""
colors = Colors()
# Převedení na list, pokud je vstup string
if isinstance(pkgs, str):
pkgs = [pkgs]
total_pkgs = len(pkgs)
failed_pkgs = []
print_status(f"Preparing to install {total_pkgs} package(s) using {repo}", "info")
# Příprava příkazu podle package manageru
if repo == "apt":
pkgs = ["steam-installer" if pkg == "steam" else pkg for pkg in pkgs]
pkg_str = " ".join(pkgs)
cmd = f"sudo nala install {pkg_str} -y" if shutil.which("nala") else f"sudo apt install {pkg_str} -y"
elif repo == "dnf":
pkg_str = " ".join(pkgs)
cmd = f"sudo dnf install {pkg_str} -y"
elif repo == "pacman":
pkg_str = " ".join(pkgs)
cmd = f"sudo pacman -S --noconfirm {pkg_str}"
elif repo == "zypper":
pkg_str = " ".join(pkgs)
cmd = f"sudo zypper install {pkg_str} -y"
elif repo == "yay":
pkg_str = " ".join(pkgs)
cmd = f"yay -S --noconfirm {pkg_str}"
elif repo == "paru":
pkg_str = " ".join(pkgs)
cmd = f"paru -S --noconfirm {pkg_str}"
elif repo == "flatpak":
pkg_str = " ".join(pkgs)
cmd = f"flatpak install flathub {pkg_str} -y"
elif repo == "snap":
pkg_str = " ".join(pkgs)
cmd = f"sudo snap install {pkg_str}"
elif repo == "brew":
pkg_str = " ".join(pkgs)
cmd = f"brew install {pkg_str}"
elif repo == "pacstall":
pkg_str = " ".join(pkgs)
cmd = f"pacstall -I {pkg_str}"
elif repo == "betterpkg":
# Pro Better-pkg použijeme příkaz pro instalaci z verified_urls.json
argsi = argparse.Namespace()
argsi.package = pkgs
argsi.fetch = True
argsi.y = True
install(argsi)
else:
print_status(f"Unsupported package manager: {repo}", "error")
return
# Instalace balíčků
print_status(f"Installing packages using {repo}...", "info")
print(f"\n{colors.BWhite}Packages to install:{colors.NC}")
for pkg in pkgs:
print(f"{colors.BPurple} • {pkg}{colors.NC}")
print()
try:
process = subprocess.Popen(
cmd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
universal_newlines=True,
bufsize=1
)
current_pkg = 1
while True:
output = process.stdout.readline()
if output == '' and process.poll() is not None:
break
if output:
# Detekce aktuálního balíčku podle výstupu
for pkg in pkgs:
if pkg.lower() in output.lower():
current_pkg += 1
print(output.strip())
return_code = process.poll()
if return_code == 0:
print()
print_status("Installation completed successfully", "success")
print(f"\n{colors.BWhite}Successfully installed packages:{colors.NC}")
for pkg in pkgs:
print(f"{colors.BGreen} • {pkg}{colors.NC}")
log_history("install", pkg, repo)
else:
print_status("Installation failed", "error")
print(f"\n{colors.BWhite}Failed to install packages:{colors.NC}")
for pkg in pkgs:
print(f"{colors.BRed} • {pkg}{colors.NC}")
except Exception as e:
print_status(f"Error during installation: {str(e)}", "error")
if failed_pkgs:
print(f"\n{colors.BYellow}Warning: The following packages failed to install:{colors.NC}")
for pkg in failed_pkgs:
print(f"{colors.BRed} • {pkg}{colors.NC}")
# Shrnutí instalace
print(f"\n{colors.BWhite}Installation Summary:{colors.NC}")
print(f"{colors.BCyan}Total packages processed: {total_pkgs}{colors.NC}")
print(f"{colors.BGreen}Successfully installed: {total_pkgs - len(failed_pkgs)}{colors.NC}")
if failed_pkgs:
print(f"{colors.BRed}Failed installations: {len(failed_pkgs)}{colors.NC}")
def remove_package(pkgs, repo):
"""Odstraňuje balíčky podle správce balíčků."""
colors = Colors()
# Převedení na list, pokud je vstup string
if isinstance(pkgs, str):
pkgs = [pkgs]
total_pkgs = len(pkgs)
failed_pkgs = []
print_status(f"Preparing to remove {total_pkgs} package(s) using {repo}", "info")
# Příprava příkazu podle package manageru
if repo == "apt":
pkg_str = " ".join(pkgs)
cmd = f"sudo nala remove {pkg_str} -y" if shutil.which("nala") else f"sudo apt remove {pkg_str} -y"
elif repo == "dnf":
pkg_str = " ".join(pkgs)
cmd = f"sudo dnf remove {pkg_str} -y"
elif repo == "pacman":
pkg_str = " ".join(pkgs)
cmd = f"sudo pacman -R --noconfirm {pkg_str}"
elif repo == "zypper":
pkg_str = " ".join(pkgs)
cmd = f"sudo zypper remove {pkg_str} -y"
elif repo == "yay":
pkg_str = " ".join(pkgs)
cmd = f"yay -R --noconfirm {pkg_str}"
elif repo == "paru":
pkg_str = " ".join(pkgs)
cmd = f"paru -R --noconfirm {pkg_str}"
elif repo == "flatpak":
pkg_str = " ".join(pkgs)
cmd = f"flatpak remove flathub {pkg_str} -y"
elif repo == "snap":
pkg_str = " ".join(pkgs)
cmd = f"sudo snap remove {pkg_str}"
elif repo == "brew":
pkg_str = " ".join(pkgs)
cmd = f"brew remove {pkg_str}"
elif repo == "pacstall":
pkg_str = " ".join(pkgs)
cmd = f"pacstall -R {pkg_str}"
elif repo == "betterpkg":
pkg_str = " ".join(pkgs)
if shutil.which("apt"):
cmd = f"sudo nala remove {pkg_str} -y" if shutil.which("nala") else f"sudo apt remove {pkg_str} -y"
elif shutil.which("dnf"):
cmd = f"sudo dnf remove {pkg_str} -y"
elif shutil.which("zypper"):
cmd = f"sudo zypper remove {pkg_str} -y"
else:
print_status(f"Unsupported package manager: {repo}", "error")
return
# Instalace balíčků
print_status(f"Removing packages using {repo}...", "info")
print(f"\n{colors.BWhite}Packages to remove:{colors.NC}")
for pkg in pkgs:
print(f"{colors.BPurple} • {pkg}{colors.NC}")
print()
try:
process = subprocess.Popen(
cmd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
universal_newlines=True,
bufsize=1
)
current_pkg = 1
while True:
output = process.stdout.readline()
if output == '' and process.poll() is not None:
break
if output:
# Detekce aktuálního balíčku podle výstupu
for pkg in pkgs:
if pkg.lower() in output.lower():
current_pkg += 1
print(output.strip())
return_code = process.poll()
if return_code == 0:
print() # Nový řádek po progress baru
print_status("Remove completed successfully", "success")
print(f"\n{colors.BWhite}Successfully removed packages:{colors.NC}")
for pkg in pkgs:
print(f"{colors.BGreen} • {pkg}{colors.NC}")
log_history("remove", pkg, repo)
else:
print_status("Remove failed", "error")
print(f"\n{colors.BWhite}Failed to remove packages:{colors.NC}")
for pkg in pkgs:
print(f"{colors.BRed} • {pkg}{colors.NC}")
except Exception as e:
print_status(f"Error during remove: {str(e)}", "error")
if failed_pkgs:
print(f"\n{colors.BYellow}Warning: The following packages failed to remove:{colors.NC}")
for pkg in failed_pkgs:
print(f"{colors.BRed} • {pkg}{colors.NC}")
# Shrnutí odinstalace
print(f"\n{colors.BWhite}Remove Summary:{colors.NC}")
print(f"{colors.BCyan}Total packages processed: {total_pkgs}{colors.NC}")
print(f"{colors.BGreen}Successfully removed: {total_pkgs - len(failed_pkgs)}{colors.NC}")
if failed_pkgs:
print(f"{colors.BRed}Failed to remove: {len(failed_pkgs)}{colors.NC}")
# hlavní funkce
def handle_update(args):
colors = Colors()
if not args.y:
confirm = input(f"{colors.BYellow}Are you sure you want to update all packages? (y/N) {colors.NC}").strip().lower()
if not confirm.startswith('y'):
sys.exit(1)
# Před spuštěním příkazů, které se mají spustit před aktualizací
if PRE_UPDATE_COMMANDS:
for cmd in PRE_UPDATE_COMMANDS:
print(f"Running pre-update command: {cmd}")
try:
subprocess.run(cmd, shell=True, check=True)
print(f"Pre-update command executed: {cmd}")
except subprocess.CalledProcessError:
print(f"Error during pre-update command: {cmd}")
return
def update_system_packages():
print_status("Updating system packages...")
try:
if shutil.which("nala"):
cmd = "sudo nala upgrade --full --no-autoremove -o Acquire::AllowReleaseInfoChange=true"
cmd += " -y" if args.y else ""
pm = "apt"
elif shutil.which("garuda-update"):
cmd = f"sudo garuda-update{' --noconfirm' if args.y else ''}"
pm = "pacman"
elif shutil.which("bootc"):
cmd = f"sudo bootc update{' -y' if args.y else ''}"
pm = "rpm-ostree"
elif shutil.which("rpm-ostree"):
cmd = f"sudo rpm-ostree update{' -y' if args.y else ''}"
pm = "rpm-ostree"
elif shutil.which("dnf"):
cmd = f"sudo dnf update{' -y' if args.y else ''}"
pm = "dnf"
elif shutil.which("pacman"):
cmd = "sudo pacman -Syu --noconfirm"
pm = "pacman"
elif shutil.which("zypper"):
cmd = f"sudo zypper update{' -y' if args.y else ''}"
pm = "zypper"
else:
cmd = f"sudo apt update --allow-releaseinfo-change && sudo apt upgrade{' -y' if args.y else ''}"
pm = "apt"
process = subprocess.run(cmd, shell=True, check=True)
print_status("System update completed successfully", "success")
log_history("update", "all", pm)
return True
except subprocess.CalledProcessError:
print_status("Error during system update", "error")
return False
def update_additional_packages():
package_managers = {
"pacstall": "sudo pacstall -Up",
"yay": "yay -Sua --noconfirm",
"paru": "paru -Sua --noconfirm",
"flatpak": f"sudo flatpak update{' -y' if args.y else ''}",
"snap": "sudo snap refresh",
"brew": "brew upgrade"
}
for pm, cmd in package_managers.items():
if shutil.which(pm):
print_status(f"Updating {pm} packages...")
try:
subprocess.run(cmd, shell=True, check=True)
print_status(f"{pm} update completed successfully", "success")
log_history("update", "all", pm)
except subprocess.CalledProcessError:
print_status(f"Error updating {pm} packages", "error")