Clean up code slightly

This commit is contained in:
Théophile Bastian 2021-03-21 23:53:20 +01:00
parent 3ce266d97d
commit 74c133bcb9

View file

@ -27,14 +27,20 @@ VORBIS_ARG_NAME = {
class NoSuchTag(Exception): class NoSuchTag(Exception):
"""Raised when trying to reverse the `VORBIS_ARG_NAME` dict on an invalid tag name"""
def __init__(self, tag): def __init__(self, tag):
super().__init__()
self.tag = tag self.tag = tag
super(NoSuchTag, self).__init__()
def __str__(self): def __str__(self):
return "No such Vorbis tag {}".format(self.tag) return "No such Vorbis tag {}".format(self.tag)
class MetaflacError(Exception):
""" Raised when an invocation of metaflac failed. """
def argparser(): def argparser():
""" Parses the arguments from sys.argv """ """ Parses the arguments from sys.argv """
parser = argparse.ArgumentParser( parser = argparse.ArgumentParser(
@ -63,12 +69,14 @@ def is_flac_file(path):
""" Checks whether `path` refers to an existing, writeable flac file """ """ Checks whether `path` refers to an existing, writeable flac file """
if not os.path.isfile(path) or not os.access(path, os.W_OK): if not os.path.isfile(path) or not os.access(path, os.W_OK):
return False return False
flac_run = subprocess.run( try:
["metaflac", "--list", path], subprocess.run(
stdout=subprocess.DEVNULL, ["metaflac", "--list", path],
stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
) stderr=subprocess.DEVNULL,
if flac_run.returncode != 0: check=True,
)
except subprocess.CalledProcessError:
return False # Metaflac failed to list the files' metadata return False # Metaflac failed to list the files' metadata
return True return True
@ -94,18 +102,14 @@ def edit_flac(args):
metaflac_args = make_metaflac_args(args) metaflac_args = make_metaflac_args(args)
metaflac_args += args["file"] metaflac_args += args["file"]
metaflac_args.insert(0, "metaflac") metaflac_args.insert(0, "metaflac")
metaflac_run = subprocess.run(metaflac_args) try:
subprocess.run(metaflac_args, check=True)
if metaflac_run.returncode != 0: except subprocess.CalledProcessError as exn:
print( raise MetaflacError(
( "Failed to edit tags: metaflac exited with error {}. Output:\n{}".format(
"\n\nMetaflac exited with return code {}. There was an error " exn.returncode, exn.stderr
"during the execution, you should look at the output to " )
"investigate it." ) from exn
).format(metaflac_run.returncode),
file=sys.stderr,
)
sys.exit(metaflac_run.returncode)
def reverse_tag(vorbis_tag): def reverse_tag(vorbis_tag):
@ -123,7 +127,15 @@ def get_tags(path):
metaflac_args += ["--show-tag", VORBIS_ARG_NAME[tag]] metaflac_args += ["--show-tag", VORBIS_ARG_NAME[tag]]
metaflac_args.append(path) metaflac_args.append(path)
metaflac_run = subprocess.run(metaflac_args, stdout=subprocess.PIPE) try:
metaflac_run = subprocess.run(metaflac_args, check=True, stdout=subprocess.PIPE)
except subprocess.CalledProcessError as exn:
raise MetaflacError(
(
"Failed to get tags for {}: metaflac exited with error {}."
"Output:\n{}"
).format(path, exn.returncode, exn.stderr)
) from exn
meta_out = metaflac_run.stdout.decode("utf-8") meta_out = metaflac_run.stdout.decode("utf-8")
output = {} output = {}
@ -142,13 +154,14 @@ def show_tags(path):
tags = get_tags(path) tags = get_tags(path)
print("File: {}".format(path)) print("File: {}".format(path))
max_len = max([len(tag) for tag in tags]) tag_len = max([len(tag) for tag in tags]) + 1
for tag in tags: for tag in tags:
print(" {}: {}{}".format(tag, " " * (max_len - len(tag)), tags[tag])) print((" {:<" + str(tag_len) + "} {}").format(tag + ":", tags[tag]))
print("") print("")
def main(): def main():
""" Entrypoint function """
args = vars(argparser()) args = vars(argparser())
has_errors = False has_errors = False