Split command-line-generating code into its own function

This commit is contained in:
Eric Torres 2019-02-02 17:10:45 -08:00
parent 0574ec032b
commit 4b285401ed

View File

@ -7,7 +7,6 @@ import subprocess
# ========== Constants ==========
REPO_ADD_CMD = '/usr/bin/repo-add'
REPO_REMOVE_CMD = '/usr/bin/repo-remove'
DB_EXT = 'db.tar.xz'
# ========== Logging setup ==========
syslog = logging.getLogger(__name__)
@ -19,6 +18,41 @@ class RepoAddError(BaseException):
# ========== Functions ==========
def gen_cmdline(operation, db, opts, *pkgs):
"""Generate a command suitable for invoking either repo-add or
repo-remove.
:param operation: run either repo-add or repo-remove
:type operation: str
:param db: the database file to operate on
:type db: str, bytes, or path-like object
:param opts: extra options to pass to repo-add
:type opts: list
:param pkgs: these arguments depend on whether the operation is
an add or remove.
If operation is 'add', then pkgs is all of the paths of the
package files to add to the database. If operation is 'remove',
then pkgs is the name of the packages to remove from the database.
:type pkgs: any iterable
:returns: list of command-line arguments suitable for passing to
subprocess.run()
:rtype: list
:raises: ValueError if operation was invalid
"""
if not operation == 'add' or operation == 'remove':
raise ValueError('Invalid operation was raised')
cmd = [f"/usr/bin/repo-{operation}"]
if opts is not None:
cmd.extend(opts)
cmd.append(db)
cmd.extend(pkgs)
return cmd
def repo_add(operation, db, *pkgs, opts=None):
"""Run repo-add.
@ -43,29 +77,21 @@ def repo_add(operation, db, *pkgs, opts=None):
"""
if operation == 'add':
syslog.info('Adding packages to database')
cmd = [REPO_ADD_CMD]
else:
syslog.info('Removing packages from database')
cmd = [REPO_REMOVE_CMD]
syslog.debug(f"Database: {db}")
syslog.debug(f"Options: {opts}")
syslog.debug(f"Packages: {pkgs}")
if opts is not None:
cmd.extend(opts)
cmd.append(db)
cmd.extend(pkgs)
syslog.debug(f"Final repo-add command: {cmd}")
try:
cmd = gen_cmdline(operation, db, opts, *pkgs)
process = subprocess.run(cmd,
check=True,
capture_output=True,
text=True)
except RepoAddError:
except subprocess.CalledProcessError:
raise RepoAddError(process.stderr)
else:
syslog.debug(process.stdout)
syslog.info('Finished adding packages to database')
syslog.info('Database operation complete')