-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapttool.py
executable file
·2142 lines (1872 loc) · 68.9 KB
/
apttool.py
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
# -*- coding: utf-8 -*-
""" apttool.py
Provides a few apt-related functions based on the 'apt' module.
-Christopher Welborn 06-??-2013
Revisited: 4-7-2019
"""
from collections import namedtuple, UserList
from contextlib import suppress
from datetime import datetime
from enum import Enum
import os
import re
import stat
import struct
import sys
from time import time
def import_err(name, exc, module=None):
""" Print an error message about missing third-party libs and exit. """
module = module or name.lower()
# Get actual module name from exception if possible, for when dependencies
# are not installed.
namepat = re.compile('cannot import name \'(?P<name>[^\']+)\'')
namematch = namepat.search(str(exc))
excname = None
if namematch is not None:
excname = namematch.groupdict().get('name', None)
modname = exc.name or excname
propername = name if name.lower() == str(modname).lower() else modname
print(
'\n'.join((
'Missing important third-party library: {name}',
'This can be installed with `pip`: pip install {module}',
'\nError message: {exc}'
)).format(
name=propername,
module=modname if (modname and modname != module) else module,
exc=exc,
),
file=sys.stderr
)
if modname and (modname != module):
print(
'\n'.join((
'\n{name} depends on {module} to run correctly.',
)).format(
name=name,
module=modname,
),
file=sys.stderr,
)
sys.exit(1)
try:
import apt # apt tools
import apt.progress.text # apt tools
except ImportError as ex:
import_err('apt', ex)
try:
import apt_pkg # for IterCache()
from apt_pkg import gettext as _ # for IterCache()
except ImportError as ex:
import_err('apt_pkg', ex)
try:
from colr import (
auto_disable as colr_auto_disable,
Colr,
disable as colr_disable,
docopt,
strip_codes,
AnimatedProgress,
Frames,
)
# Aliased for easier typing and shorter lines.
C = Colr
except ImportError as excolr:
import_err('Colr', excolr)
try:
from fmtblock import FormatBlock
except ImportError as exfmtblk:
import_err('FormatBlock', exfmtblk, module='formatblock')
# ------------------------------- End Imports -------------------------------
__version__ = '1.0.0'
NAME = 'AptTool'
# Get short script name.
SCRIPT = os.path.split(sys.argv[0])[-1]
USAGESTR = """{name} v. {version}
Usage:
{script} -? | -h | -v
{script} -c file [-C] [-n] [-q]
{script} (-i | -d | -p) PACKAGES... [-C] [-q]
{script} (-e | -f | -S) PACKAGES... [-C] [-q] [-s]
{script} (-P | -R) PACKAGES... [-C] [-I | -N] [-q] [-s]
{script} -H [QUERY] [COUNT] [-C] [-q]
{script} (-l | -L) PACKAGES... [-C] [-q] [-s]
{script} -u [-C] [-q]
{script} -V PACKAGES... [-C] [-a] [-q] [-s]
{script} PATTERNS... [-a] [-C] [-I | -N] [-D] [-n] [-q] [-r] [-s] [-x]
Options:
COUNT : Number of history lines to return.
PACKAGES : One or many package names to try.
If a file name is given, the names
are read from the file. If '-' is
given, names are read from stdin.
PATTERNS : One or more text/regex patterns to
search for. Multiple patterns will be
joined with (.+)? if -a is used,
otherwise they are joined with |.
QUERY : Query to filter history with. The
default is 'installed'.
-a,--all : When viewing package version, list all
available versions.
When searching, join all patterns so
they must all be found in the exact
argument order.
Like doing (arg1)(.+)?(arg2).
-c file,--containsfile file : Search all installed packages for an
installed file using regex or text.
-C,--nocolor : Disable colors always.
-d,--delete : Uninstall/delete/remove a package.
-D,--dev : Search for development packages.
-e,--executables : Show installed executables for a
package.
It just shows files installed to
/bin directories.
-f,--files : Show installed files for package.
-?,--examples : Show specific usage examples and exit.
-h,--help : Show this help message and exit.
-H,--history : Show package history.
(installs, uninstalls, etc.)
-i,--install : Install a package.
-I,--INSTALLED : When searching for a package, only
include installed packages.
-l,--locate : Determine whether or not a package
exists. You can pass a file name to
read from, or use - for stdin.
Otherwise a full package name is
needed. Multiple names can be passed.
-L,--LOCATE : Same as --locate, but only shows
existing packages that are found.
-n,--names : When searching for packages, only
search names, not descriptions.
When searching with -c, don't use the
full file path, only the file name.
-N,--NOTINSTALLED : When searching for a package, only
include non-installed packages.
-p,--purge : Purge the package completely,
remove all configuration.
-P,--dependencies : List all dependencies for a package.
-q,--quiet : Don't print extra status messages.
-r,--reverse : When searching, return packages that
DON'T match.
-R,--reversedeps : Show reverse dependencies.
-s,--short : Use shorter output.
When searching, don't print the
description.
When locating, don't show the install
state.
-S,--suggests : Show package suggestions.
-u,--update : Update the cache.
..Just like `apt-get update`.
-v,--version : Show version and exit.
-V,--VERSION : Show a package's installed or available
versions.
-x,--ignorecase : Make the search query case-insensitive.
""".format(name=NAME, script=SCRIPT, version=__version__)
class NothingSingleton(object):
""" A value to use as None, where None may actually have a meaning. """
def __str__(self):
return '<Nothing>'
Nothing = NothingSingleton()
# GLOBALS ------------------------------------------------
# placeholder for global cache
cache_main = None
# Tuple for dependency_info() returns.
DependencyInfo = namedtuple(
'DependencyInfo',
('package', 'version', 'relation')
)
# Set default terminal width/height (set with get_terminal_size() later).
TERM_WIDTH, TERM_HEIGHT = 80, 120
# MAIN ---------------------------------------------------
def main(argd):
""" Main entry point for apttool """
global cache_main, oprogress, fprogress, print_status, print_status_err
if argd['--nocolor']:
colr_disable()
if argd['--quiet']:
print_status = print_status_err = noop
# Non-cache related args.
if argd['--examples']:
print_example_usage()
return 0
# Search.
if argd['PATTERNS']:
query = query_build(argd['PATTERNS'], all_patterns=argd['--all'])
return cmd_search(
query,
use_desc=not argd['--names'],
print_no_desc=argd['--short'],
install_state=InstallStateEnum.from_argd(argd),
case_insensitive=argd['--ignorecase'],
dev_only=argd['--dev'],
reverse=argd['--reverse']
)
if argd['--history']:
# Just show apt history and exit.
cnt = argd['COUNT']
if cnt:
try:
cnt = int(cnt)
if cnt < 1:
raise ValueError('Must be greater than 0!')
except (TypeError, ValueError) as exint:
print_err(
'\nInvalid number for count: {}\n{}'.format(cnt, exint)
)
return 1
return cmd_history(argd['QUERY'], count=cnt)
# -----v-- Actions that may benefit from cache pre-loading --v------
return run_preload_cmd(argd)
# FUNCTIONS -----------------------------------------------
def noop(*args, **kwargs):
""" Any function can be disabled by replacing it with this no-op function.
Used for silencing print_status.
"""
return None
def cache_get(self, item, default=Nothing):
""" Supplies Cache.get()
To monkeypatch apt.Cache to act like a dict with .get()
"""
try:
val = self[item]
except KeyError:
if default is Nothing:
raise
return default
return val
def cache_load(forced=False):
""" Load apt.Cache(), setting global `cache_main`.
Returns `cache_main`.
Arguments:
forced : Reload cache, even if cache_main is loaded already.
"""
global cache_main
if forced or (cache_main is None):
cache_main = apt.Cache(memonly=True)
return cache_main
def cmd_contains_file(name, shortnamesonly=False):
""" Search all installed files for a filename.
Print packages containing matches.
Arguments:
name : Name or part of a name to search for
Keyword Arguments:
shortnamesonly : don't include the full path in search,
just the short file name.
"""
try:
repat = re.compile(name)
except Exception as ex:
print_err('\nInvalid search term!: {}\n{}'.format(name, ex))
return 1
print_status(
'Looking for packages by file pattern',
value=repat.pattern,
)
# Setup filename methods (long or short, removes an 'if' from the loop.)
def getfilenameshort(s):
return os.path.split(s)[-1]
# Pick filename retrieval function..
filenamefunc = getfilenameshort if shortnamesonly else str
# Iterate all packages...
totalpkgs = 0
totalfiles = 0
for pkgname in cache_main.keys():
pkg = cache_main[pkgname]
matchingfiles = []
if not pkg_install_state(pkg):
continue
if not hasattr(pkg, 'installed_files'):
print_err(
'\n'.join((
'\nUnable to retrieve installed files for {},',
'apt/apt_pkg may be out of date!'
)).format(pkgname)
)
return 1
for installedfile in (pkg.installed_files or []):
shortname = filenamefunc(installedfile)
rematch = repat.search(shortname)
if rematch:
# Save match for report,
# (report when we're finished with this package.)
matchingfiles.append(installedfile)
# Report any matches.
if matchingfiles:
totalpkgs += 1
totalfiles += len(matchingfiles)
print(pkg_format(pkg, no_desc=True, no_marker=True))
print(' {}'.format('\n '.join(matchingfiles)))
pluralfiles = 'file' if totalfiles == 1 else 'files'
pluralpkgs = 'package.' if totalpkgs == 1 else 'packages.'
print_status(
'\nFound',
C(totalfiles, fore='blue', style='bright'),
pluralfiles,
'in',
C(totalpkgs, fore='blue', style='bright'),
pluralpkgs,
)
return 0
def cmd_dependencies(pkgname, installstate=None, short=False):
""" Print all dependencies for a package.
Optionally, filter by installed or uninstalled.
Arguments:
pkgname : (str) Package name to check dependencies for.
installstate : InstallStateEnum, to filter dependency list.
Default: InstallStateEnum.every
short : Use shorter output.
"""
status = noop if short else print_status
installstate = installstate or InstallStateEnum.every
package = cache_main.get(pkgname, None)
if package is None:
print_err('\nCan\'t find a package by that name: {}'.format(pkgname))
return 1
totalstate = 0
total = 0
for pkgver in package.versions:
status(
'\n{} dependencies for {} v. {}'.format(
str(installstate).title(),
package.name,
pkgver.version))
for deplst in pkgver.dependencies:
total += 1
for dep in installstate.filter_pkgs(deplst):
depinfo = dependency_info(dep, default=dep.name)
print(
pkg_format(
depinfo.package,
no_ver=short,
no_desc=short,
use_version=depinfo.version,
use_relation=depinfo.relation,
)
)
totalstate += 1
if installstate == InstallStateEnum.every:
status('\nTotal: {}'.format(total))
else:
statestr = str(installstate).title()
status('\nTotal: {}, {}: {}'.format(total, statestr, totalstate))
return 0 if totalstate > 0 else 1
def cmd_history(filtertext=None, count=None):
""" Search dpkg log for lines containing text, print the formatted lines.
If filtertext is None, all lines are formatted and printed.
"""
repat = None
if filtertext is not None:
try:
repat = re.compile(filtertext)
except re.error as exre:
print_err('Invalid filter text: {}\n{}'.format(filtertext, exre))
return False
if count:
def cnt_exceeded(i):
return i >= count
else:
def cnt_exceeded(i):
# Count is never exceeded
return False
total = 0
try:
for historyline in iter_history():
if historyline.matches(repat):
total += 1
print(str(historyline))
if cnt_exceeded(total):
break
entryplural = 'entry' if total == 1 else 'entries'
print_status('\nFound {} {}.'.format(total, entryplural))
except (EnvironmentError, FileNotFoundError, re.error) as excancel:
print_err('\nUnable to retrieve history:\n {}'.format(excancel))
return False
except Exception as exgeneral:
print_err('\nUnexpected error: {}'.format(exgeneral))
return False
return True
def cmd_install(pkgname, doupdate=False):
""" Install a package. """
print_status('\nLooking for \'{}\' to install...'.format(pkgname))
if doupdate:
updateret = cmd_update()
if not updateret:
print_err('\nCan\'t update cache!')
if pkgname in cache_main.keys():
package = cache_main[pkgname]
if pkg_install_state(package):
print_err(
'\nThis package is already installed: {}'.format(package.name)
)
return 1
print_status('Installing package: {}'.format(package.name))
# Mark for install.
if not hasattr(package, 'mark_install'):
print_err(
'\napt_pkg doesn\'t have \'mark_install\' attribute, '
'apt/apt_pkg module may be out of date.\n'
'Stopping.')
return 1
cache_main[pkgname].mark_install()
# Install the package
try:
cache_main.commit(
fetch_progress=SimpleFetchProgress(),
install_progress=SimpleInstallProgress(
pkgname=pkgname))
except apt.cache.LockFailedException as exlock:
print_err(
'\n'.join((
'\nCan\'t install package!',
'Make sure you have proper permissions. (are you root?)',
'\nError Message:\n{}'
)).format(exlock))
return 1
except SystemError as exsys:
# dpkg is already being used by something else.
print_err(
'\n'.join((
'\nCan\'t install package!',
'Make sure all other package managers are closed.',
'\nError Message:\n{}'
)).format(exsys))
return 1
else:
print_err('\nCan\'t find a package by that name: {}'.format(pkgname))
return 1
return 0
def cmd_installed_files(pkgname, execs_only=False, short=False):
""" Print a list of installed files for a package. """
status = noop if short else print_status
try:
package = cache_main[pkgname]
except KeyError:
print_missing_pkg(pkgname)
return 1
if not pkg_install_state(package):
print_err(
'\nThis package is not installed: {}'.format(
C(package.name, 'blue')
),
'\nCan\'t get installed files for ',
'uninstalled packages.',
sep=''
)
return 1
if not hasattr(package, 'installed_files'):
print_err(''.join((
'\nUnable to get installed files for {}',
', apt/apt_pkg module may be out of date.'
)).format(package.name))
return 1
files = sorted(fname for fname in package.installed_files if fname)
if execs_only:
# Show executables only (/bin directory files.)
# Returns true for a path if it looks like an executable.
# is_exec = lambda s: ('/bin' in s) and (not s.endswith('/bin'))
files = [fname for fname in files if is_executable(fname)]
label = 'executable' if len(files) == 1 else 'executables'
else:
# Show installed files.
label = 'installed file' if len(files) == 1 else 'installed files'
if files:
status('Found {} {} for {}:'.format(len(files), label, package.name))
if short:
print('\n'.join(sorted(files)))
else:
print(' {}\n'.format('\n '.join(sorted(files))))
return 0
# No files found (possibly after trimming to only executables)
print_status_err('Found 0 {} for: {}'.format(label, package.name))
return 1
def cmd_locate(pkgnames, only_existing=False, short=False):
""" Locate one or more packages.
Arguments:
pkgnames : A list of package names, or file names to read
from. If '-' is encountered in the list then
stdin is used. stdin can only be used once.
only_existing : Only show existing packages.
short : When truthy, do not print the install state.
"""
existing = 0
checked = 0
for pname in pkgnames:
pname = pname.lower().strip()
# Use Package for existing, packagename for missing.
pkg = cache_main.get(pname, pname)
if pkg != pname:
existing += 1
elif only_existing:
continue
print(pkg_format(
pkg,
color_missing=True,
no_marker=short,
no_desc=short
))
checked += 1
plural = 'package' if existing == 1 else 'packages'
print_status('\nFound {} of {} {}.'.format(existing, checked, plural))
return 0 if (checked > 0) and (existing == checked) else 1
def cmd_remove(pkgname, purge=False):
""" Remove or Purge a package by name """
print_status('\nLooking for \'{}\' to remove...'.format(pkgname))
if purge:
opaction = 'purge'
opstatus = 'Purging'
else:
opaction = 'remove'
opstatus = 'Removing'
try:
package = cache_main[pkgname]
except KeyError:
print_missing_pkg(pkgname)
return 1
if not pkg_install_state(package):
print_err('\nThis package is not installed: {}'.format(package.name))
return 1
print_status('Removing package: {}'.format(package.name))
# Mark for delete.
if not hasattr(package, 'mark_delete'):
print_err(
'\n'.join((
'\napt_pkg doesn\'t have \'mark_delete\' attribute,',
'apt/apt_pkg module may be out of date.',
'\nStopping.'
))
)
return 1
package.mark_delete(purge=purge)
# Remove the package
try:
cache_main.commit(
fetch_progress=SimpleFetchProgress(),
install_progress=SimpleInstallProgress(
pkgname=pkgname,
msg=opstatus))
return 0
except apt.cache.LockFailedException as exlock:
print_err(
'\n'.join((
'\nCan\'t {} package, ',
'Make sure you have proper permissions. (are you root?)',
'\nError Message:\n{}',
)).format(opaction, exlock)
)
return 1
except SystemError as exsys:
# dpkg is already being used by something else.
print_err(
'\n'.join((
'Can\'t {} package, ',
'Make sure all other package managers are closed.',
'\nError Message:\n{}',
)).format(opaction, exsys)
)
return 1
def cmd_reverse_dependencies(pkgname, installstate=None, short=False):
""" Print all reverse dependencies for a package.
Optionally, filter by installed or uninstalled.
Arguments:
pkgname : (str) Package name to check dependencies for.
installstate : InstallStateEnum, to filter dependency list.
Default: InstallStateEnum.every
short : Use shorter output.
"""
status = noop if short else print_status
installstate = installstate or InstallStateEnum.every
try:
package = cache_main[pkgname]
except KeyError:
print_missing_pkg(pkgname)
return 1
status('\nSearching for {} dependents on {}...'.format(
installstate,
package.name))
totalstate = 0
total = 0
for pkg in installstate.filter_pkgs(cache_main):
for pkgver in pkg.versions:
for deplst in pkgver.dependencies:
total += 1
for dep in filter(lambda d: d.name == package.name, deplst):
print(pkg_format(pkg, no_ver=short, no_desc=short))
totalstate += 1
if installstate == InstallStateEnum.every:
status('\nTotal: {}'.format(total))
else:
statestr = str(installstate).title()
status('\nTotal: {}, {}: {}'.format(total, statestr, totalstate))
return 0 if totalstate > 0 else 1
def cmd_search(
query, use_desc=True, print_no_desc=False, print_no_ver=False,
install_state=None, case_insensitive=False, dev_only=False,
reverse=False):
""" print results while searching the cache...
Arguments:
query : Seach term for package name/desc.
use_desc : Whether to search inside pkg descs.
Default: True
print_no_desc : If True, don't print descriptions of packages.
Default: False
print_no_ver : If True, don't print the latest versions.
Default: False
install_state : InstallStateEnum to filter packages.
Default: InstallStateEnum.every
case_insensitive : Whether searches are case insensitive.
dev_only : Whether to search only dev packages.
reverse : Reverses the match, to show packages that
DON'T match the pattern.
"""
try:
re_pat = re.compile(
query,
re.IGNORECASE if case_insensitive else 0)
except re.error as ex:
raise BadSearchQuery(query, ex)
if sys.stdout.isatty():
spinner = AnimatedProgress(
'Loading APT Cache...',
fmt=' {frame} {elapsed:<2.0f}s {text}',
frames=Frames.dots_orbit.as_gradient(name='blue', style='bright'),
)
with spinner:
cache = apt.cache.FilteredCache(progress=oprogress)
else:
# No animated spinner, stdout is not a tty.
cache = apt.cache.FilteredCache(progress=oprogress)
msg = C('').join(
C('Searching ', 'blue'),
C(install_state),
' ({})'.format(C('names only', 'blue')) if not use_desc else '',
' ({})'.format(C('dev only', '#FFBB00')) if dev_only else '',
' {}'.format(C(query, 'cyan')),
(
' ({})'.format(C('case-insensitive', 'red'))
if case_insensitive
else ''
),
)
print_status(msg)
cache.set_filter(AptToolFilter(
re_pat,
_name_pat=re.compile(r'(.+dev)') if dev_only else None,
use_desc=use_desc,
install_state=install_state,
reverse=reverse,
print_no_desc=print_no_desc,
print_no_ver=print_no_ver,
))
result_cnt = len(cache)
print_status('\nFinished searching, found {} {}.'.format(
str(result_cnt),
'result' if result_cnt == 1 else 'results'
))
return 0
def cmd_suggests(pkgname, short=False, indent=0):
""" Print suggested packages for a single Package.
Return an exit status code.
Arguments:
pkgname : Package name to get suggests for.
short : If True, do not print versions/descriptions.
Default: False
indent : Amount of indent for formatted package lines.
Default: 0
"""
try:
pkg = cache_main[pkgname]
except KeyError:
print_missing_pkg(pkgname)
return 1
format_args = {
'no_desc': short,
'no_ver': short,
'indent': indent,
}
suggests = get_suggests(pkg)
suggestlen = sum(len(basedeps) for basedeps in suggests)
print_status(
'\nSuggested packages for {} ({}):'.format(pkgname, suggestlen)
)
results = 0
missing = 0
try:
for dep in suggests:
for basedep in dep:
deppkg = cache_main.get(basedep.name, None)
if deppkg is None:
# pkg_format accepts a str (name) to print missing pkgs.
deppkg = basedep.name
missing += 1
results += 1
print('\n{}'.format(pkg_format(deppkg, **format_args)))
except KeyboardInterrupt:
# User cancelled, print the result count anyway.
print_err('\nUser cancelled.\n')
if missing > 0:
# Show a warning for missing packages.
print_status_err(
'\n{} suggested {} for {} are not in the cache.'.format(
missing,
'package' if missing == 1 else 'packages',
pkgname
)
)
print_status('\nFound {} suggested {}.'.format(
results,
'package' if results == 1 else 'packages'
))
return 0 if (results > 0) else 1
def cmd_update(load_cache=False):
""" update the cache,
init or re-initialize the cache if load_cache is True
"""
global cache_main
if load_cache:
cache_load()
try:
cache_main.update(SimpleFetchProgress(msg='Updating...'))
cache_main.open(progress=SimpleOpProgress(msg='Opening cache...'))
print_status('Loaded ' + str(len(cache_main.keys())) + ' packages.')
except KeyboardInterrupt:
print_err('\nUser cancelled.\n')
except apt.cache.FetchFailedException as exfail:
print_err('\nFailed to complete download.\n{}'.format(exfail))
except Exception as ex:
print_err('\nError during update!:\n{0}\n'.format(ex))
return True
def cmd_version(pkgname, allversions=False, div=False, short=False):
""" Retrieve and print the current version info for a package.
Returns 0 for success, 1 for error.
"""
if (not short) and div:
print_status(C('{}'.format('-' * TERM_WIDTH)))
status = noop if short else print_status
status('\nLooking for \'{}\' versions...'.format(pkgname))
try:
package = cache_main[pkgname]
except KeyError:
print_missing_pkg(pkgname)
return 1
try:
versions = PackageVersions(package)
except (TypeError, ValueError):
print_err(''.join((
'\nUnable to retrieve versions for {}, ',
'apt/apt_pkg may be out of date.')).format(pkgname))
return 1
if allversions:
print(versions.formatted_all(header=not short))
else:
print(versions.formatted(header=not short))
if not short:
print(versions.format_desc())
return 0
def cmdmap_build(argd):
""" Return a map of {cmdline_option: function_info}. """
funcmap = {
'--containsfile': {
'func': cmd_contains_file,
'args': (argd['--containsfile'],),
'kwargs': {'shortnamesonly': argd['--names']}
},
'--dependencies': {
'func': multi_pkg_func,
'args': (
cmd_dependencies,
argd['PACKAGES']
),
'kwargs': {
'installstate': InstallStateEnum.from_argd(argd),
'short': argd['--short']
}
},
'--delete': { # --purge
'func': multi_pkg_func,
'args': (
cmd_remove,
argd['PACKAGES']
),
'kwargs': {'purge': bool(argd['--purge'])}
},
'--executables': {
'func': multi_pkg_func,
'args': (
cmd_installed_files,
argd['PACKAGES'],
),
'kwargs': {
'execs_only': True,
'short': argd['--short'] or argd['--quiet']
}
},
'--files': {
'func': multi_pkg_func,
'args': (
cmd_installed_files,
argd['PACKAGES'],
),
'kwargs': {
'short': argd['--short'] or argd['--quiet']
}
},
'--install': {
'func': multi_pkg_func,
'args': (
cmd_install,
argd['PACKAGES'],
)
},
'--locate': { # --LOCATE
'func': cmd_locate,
'args': (
parse_packages_arg(argd['PACKAGES']),
),
'kwargs': {
'only_existing': argd['--LOCATE'],
'short': argd['--short']
}
},
'--reversedeps': {
'func': multi_pkg_func,
'args': (
cmd_reverse_dependencies,
argd['PACKAGES']
),
'kwargs': {
'installstate': InstallStateEnum.from_argd(argd),
'short': argd['--short']
}
},
'--suggests': {
'func': multi_pkg_func,
'args': (
cmd_suggests,
argd['PACKAGES'],
),
'kwargs': {'short': argd['--short']}
},
'--update': {'func': cmd_update},
'--VERSION': {
'func': multi_pkg_func,
'args': (
cmd_version,
argd['PACKAGES'],
),
'kwargs': {
'allversions': argd['--all'],
'div': True,
'short': argd['--short']}
},
}
# Shared functions with different arguments:
funcmap['--purge'] = funcmap['--delete']
funcmap['--LOCATE'] = funcmap['--locate']
return funcmap
def dependency_info(dep, default=None):
""" Get the actual Package, version, and relation for a Dependency.
Returns a tuple of (Package/`default`, dep.version, dep.relation).
Arguments:
dep : Dependency object to get info for.
default : Returned as `deppkg` when an actual Package can't be
found.
"""
deppkg = cache_main.get(strip_arch(dep.name), default)
deprel = getattr(dep, 'relation', None) or ''
depver = getattr(dep, 'version', None) or ''
return DependencyInfo(deppkg, depver, deprel)
def get_latest_ver(pkg):
""" Return the latest version for a package. """
ver = get_latest_verobj(pkg)
return getattr(ver, 'version', 'unknown').strip()
def get_latest_verobj(pkg):
""" Return the latest Version object for a package. """
try:
ver = pkg.versions[0]
except AttributeError: