Skip to content

Instantly share code, notes, and snippets.

@Zren
Last active Jul 31, 2020
Embed
What would you like to do?
#!/bin/python3
# To install:
# EDITOR=nano sudoedit /usr/local/bin/apt
# Paste script with (Ctrl+Shift+V), then run following to make it executable:
# sudo chmod +x /usr/local/bin/apt
import os, sys
import re
import argparse
import subprocess
# ---
class TC: # Terminal Color
# Foreground
F_Default = "\x1b[39m"
F_Black = "\x1b[30m"
F_Red = "\x1b[31m"
F_Green = "\x1b[32m"
F_Yellow = "\x1b[33m"
F_Blue = "\x1b[34m"
F_Magenta = "\x1b[35m"
F_Cyan = "\x1b[36m"
F_LightGray = "\x1b[37m"
F_DarkGray = "\x1b[90m"
F_LightRed = "\x1b[91m"
F_LightGreen = "\x1b[92m"
F_LightYellow = "\x1b[93m"
F_LightBlue = "\x1b[94m"
F_LightMagenta = "\x1b[95m"
F_LightCyan = "\x1b[96m"
F_White = "\x1b[97m"
@staticmethod
def stripColors(str):
return re.sub('\x1b' + '\[((\d{1,2});)?(\d{1,2})m', '', str)
#---
def runcmd(cmd, callback=None):
# print(' '.join(cmd))
# cmd.append('--color=always')
if callback is None:
subprocess.run(cmd)
else:
proc = subprocess.run(
cmd,
capture_output=True,
)
if proc.stdout:
stdout = proc.stdout.decode('utf8')
callback(stdout, proc)
elif proc.stderr:
stderr = proc.stderr.decode('utf8')
sys.stderr.write(stderr)
sys.exit(proc.returncode)
def apt_history(args):
runcmd(['xdg-open', '/var/log/pacman.log'])
def apt_show(args):
runcmd(['pacman', '--color=always', '-Sii', args.regex])
def apt_install(args):
apt_show(args)
runcmd(['sudo', 'pacman', '--color=always', '-S', args.regex])
def apt_locate(args):
runcmd(['pacman', '--color=always', '-Qo', args.regex])
def apt_remove(args):
runcmd(['sudo', 'pacman', '--color=always', '-Rs', args.regex])
def apt_search(args):
def callback(stdout, proc):
firstResult = ''
onlyOneResult = True
for i, line in enumerate(stdout.splitlines()):
if i % 2 == 0:
sys.stdout.write(line)
else:
sys.stdout.write(line + '\n')
if i == 0:
firstResult = line
if i == 3:
onlyOneResult = False
# If there's only 1 result, show the package info.
if onlyOneResult:
firstResult = TC.stripColors(firstResult)
tokens = firstResult.split(' ')
firstPackage = tokens[0]
sys.stdout.write('\n')
showArgs = argparse.Namespace(regex=firstPackage)
apt_show(showArgs)
cmd = ['pacman', '--color=always', '-Ss', args.regex]
runcmd(cmd, callback)
def apt_files(args):
runcmd(['pacman', '--color=always', '-Ql', args.regex])
def apt_rdepends(args):
def callback(stdout, proc):
for i, line in enumerate(stdout.splitlines()):
if "Required By" in line:
sys.stdout.write(line + '\n')
cmd = ['pacman', '--color=always', '-Sii', args.regex]
runcmd(cmd, callback)
def apt_updates_list(args):
# runcmd(['pacman', '--color=always', '-Qu'])
import re
PKGCHAR = '[a-zA-Z0-9_:\-\.\+]'
VERCHAR = PKGCHAR
GRPCHAR = PKGCHAR
packages = {}
#--- packageName currentVersion -> nextVersion
proc = subprocess.run(
['pacman', '-Qu'],
capture_output=True,
)
if proc.stdout:
stdout = proc.stdout.decode('utf8')
p = re.compile('(' + PKGCHAR + '+) (' + VERCHAR + '+) -> (' + VERCHAR + '+)')
for line in stdout.splitlines():
m = p.match(line)
if m:
packageName = m.group(1)
packages[packageName] = {
'name': packageName,
'curVer': m.group(2),
'nextVer': m.group(3),
'groups': [],
}
else:
sys.stderr.write("invalid regex match for:\n\t{}\n".format(line))
sys.exit(proc.returncode)
elif proc.stderr:
stderr = proc.stderr.decode('utf8')
sys.stderr.write(stderr)
sys.exit(proc.returncode)
#--- group packageName
proc = subprocess.run(
['pacman', '-Qug'],
capture_output=True,
)
if proc.stdout:
stdout = proc.stdout.decode('utf8')
p = re.compile('(' + GRPCHAR + '+) (' + PKGCHAR + '+)')
for line in stdout.splitlines():
m = p.match(line)
if m:
group = m.group(1)
packageName = m.group(2)
if packageName in packages:
packages[packageName]['groups'].append(group)
else:
sys.stderr.write("invalid regex match for:\n\t{}\n".format(line))
sys.exit(proc.returncode)
elif proc.stderr:
stderr = proc.stderr.decode('utf8')
sys.stderr.write(stderr)
sys.exit(proc.returncode)
#--- packageName nextVersion (group)
for package in packages.values():
line = '{} {}'.format(package['name'], package['nextVer'])
if len(package['groups']) == 0:
if args.format == 'raw':
fmt = '{} {}'
elif args.format == 'html':
fmt = '{} {}'
else: # Terminal
fmt = '{} ' + TC.F_LightGreen + '{}' + TC.F_Default
line = fmt.format(package['name'], package['nextVer'])
else: # Has a group
if args.format == 'raw':
fmt = '{} {} ({})'
elif args.format == 'html':
fmt = '{} {} ({})'
else: # Terminal Colors
fmt = '{} ' + TC.F_LightGreen + '{} ' + TC.F_LightBlue + '({})' + TC.F_Default
line = fmt.format(package['name'], package['nextVer'], ' '.join(package['groups']))
sys.stdout.write(line + '\n')
sys.exit(0)
def main():
parser = argparse.ArgumentParser(prog='apt', description='apt commands for pacman.')
subparsers = parser.add_subparsers()
parser_install = subparsers.add_parser('history', help='apt history')
parser_install.set_defaults(func=apt_history)
parser_install = subparsers.add_parser('install', help='pacman -S')
parser_install.set_defaults(func=apt_install)
parser_install.add_argument('regex')
parser_locate = subparsers.add_parser('locate', help='pacman -Qo')
parser_locate.set_defaults(func=apt_locate)
parser_locate.add_argument('regex')
parser_remove = subparsers.add_parser('remove', help='pacman -Rs')
parser_remove.set_defaults(func=apt_remove)
parser_remove.add_argument('regex')
parser_search = subparsers.add_parser('search', help='pacman -Ss')
parser_search.set_defaults(func=apt_search)
parser_search.add_argument('regex')
parser_show = subparsers.add_parser('show', help='pacman -Sii')
parser_show.set_defaults(func=apt_show)
parser_show.add_argument('regex')
parser_files = subparsers.add_parser('files', help='pacman -Ql')
parser_files.set_defaults(func=apt_files)
parser_files.add_argument('regex')
parser_rdepends = subparsers.add_parser('rdepends', help='pacman -Sii')
parser_rdepends.set_defaults(func=apt_rdepends)
parser_rdepends.add_argument('regex')
parser_updates = subparsers.add_parser('updates', help='pacman -Qu')
parser_updates.set_defaults(func=apt_updates_list)
parser_updates.add_argument('--format', default='terminal')
args = parser.parse_args()
if 'func' in args:
try:
args.func(args)
except KeyboardInterrupt:
pass
else:
parser.print_help()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment