use f-strings where possible

This commit is contained in:
lynxize 2025-06-20 16:39:52 -06:00
parent 141f6bdeb1
commit 5047f729eb
Signed by: lynxize
GPG key ID: 8615849B8532CD77

View file

@ -13,10 +13,6 @@
# along with this program; if not, write to the Free Software # along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
from builtins import input
from builtins import map
from builtins import range
from functools import reduce
__title__ = "KeyJ's iPod shuffle Database Builder" __title__ = "KeyJ's iPod shuffle Database Builder"
__version__ = "1.0" __version__ = "1.0"
@ -67,6 +63,7 @@ __email__ = "martin.fiedler@gmx.net"
""" """
import functools, sys, os, os.path, array, random, fnmatch, operator, string import functools, sys, os, os.path, array, random, fnmatch, operator, string
from builtins import map, input, range
from io import BytesIO from io import BytesIO
from typing import TextIO from typing import TextIO
@ -149,14 +146,14 @@ def ParseRule(rule):
sep_pos = min([rule.find(sep) for sep in "~=<>" if rule.find(sep) > 0]) sep_pos = min([rule.find(sep) for sep in "~=<>" if rule.find(sep) > 0])
prop = rule[:sep_pos].strip() prop = rule[:sep_pos].strip()
if not prop in KnownProps: if not prop in KnownProps:
log("WARNING: unknown property `%s'" % prop) log(f"WARNING: unknown property '{prop}'")
return prop, rule[sep_pos], ParseValue(rule[sep_pos + 1:].strip()) return prop, rule[sep_pos], ParseValue(rule[sep_pos + 1:].strip())
def ParseAction(action): def ParseAction(action):
prop, value = list(map(str.strip, action.split('=', 1))) prop, value = list(map(str.strip, action.split('=', 1)))
if not prop in KnownProps: if not prop in KnownProps:
log("WARNING: unknown property `%s'" % prop) log(f"WARNING: unknown property '{prop}'")
return prop, ParseValue(value) return prop, ParseValue(value)
@ -174,7 +171,7 @@ def ParseRuleLine(line):
else: else:
return list(map(ParseRule, ruleset)), actions return list(map(ParseRule, ruleset)), actions
except OSError: # (ValueError,IndexError,KeyError): except OSError: # (ValueError,IndexError,KeyError):
log("WARNING: rule `%s' is malformed, ignoring" % line) log(f"WARNING: rule '{line}' is malformed, ignoring")
return None return None
@ -191,14 +188,14 @@ def rename_safely(path, name):
newname = ''.join(map(safe_char, base)) newname = ''.join(map(safe_char, base))
if name == newname + ext: if name == newname + ext:
return name return name
if os.path.exists("%s/%s%s" % (path, newname, ext)): if os.path.exists(f"{path}/{newname}{ext}"):
i = 0 i = 0
while os.path.exists("%s/%s_%d%s" % (path, newname, i, ext)): while os.path.exists(f"{path}/{newname}_{i}{ext}"):
i += 1 i += 1
newname += "_%d" % i newname += f"_{i}"
newname += ext newname += ext
try: try:
os.rename("%s/%s" % (path, name), "%s/%s" % (path, newname)) os.rename(f"{path}/{name}", f"{path}/{newname}")
except OSError: except OSError:
pass # don't fail if the rename didn't work pass # don't fail if the rename didn't work
return newname return newname
@ -220,7 +217,7 @@ def write_to_db(filename):
# check and apply rules # check and apply rules
for ruleset, action in Rules: for ruleset, action in Rules:
if reduce(operator.__and__, [MatchRule(props, rule) for rule in ruleset], True): if functools.reduce(operator.__and__, [MatchRule(props, rule) for rule in ruleset], True):
props.update(action) props.update(action)
if props['ignore']: return 0 if props['ignore']: return 0
@ -269,7 +266,7 @@ def cmp(a, b):
def file_entry(path, name, prefix=""): def file_entry(path, name, prefix=""):
if not name or name[0] == ".": return None if not name or name[0] == ".": return None
fullname = "%s/%s" % (path, name) fullname = f"{path}/{name}"
may_rename = not (fullname.startswith("./iPod_Control")) and args.rename may_rename = not (fullname.startswith("./iPod_Control")) and args.rename
try: try:
if os.path.islink(fullname): if os.path.islink(fullname):
@ -293,7 +290,7 @@ def browse(path: string, interactive: bool):
if not displaypath: displaypath = "/" if not displaypath: displaypath = "/"
while interactive: while interactive:
choice = input("include `%s'? [(Y)es, (N)o, (A)ll] " % displaypath)[:1].lower() choice = input(f"include '{displaypath}'? [(Y)es, (N)o, (A)ll] ")[:1].lower()
if not choice: continue if not choice: continue
# all/alle/tous/<dontknow> # all/alle/tous/<dontknow>
@ -310,7 +307,7 @@ def browse(path: string, interactive: bool):
subdirs = [x[2] for x in files if not x[0]] subdirs = [x[2] for x in files if not x[0]]
files = [x for x in files if x[0]] files = [x for x in files if x[0]]
for dir in subdirs: for dir in subdirs:
subpath = "%s/%s" % (path, dir) subpath = f"{path}/{dir}"
try: try:
files.extend([x for x in [ files.extend([x for x in [
file_entry(subpath, name, dir + "/") for name in os.listdir(subpath) file_entry(subpath, name, dir + "/") for name in os.listdir(subpath)
@ -323,13 +320,13 @@ def browse(path: string, interactive: bool):
real_count = 0 real_count = 0
for item in files: for item in files:
fullname = "%s/%s" % (path, item[2]) fullname = f"{path}/{item[2]}"
if item[0]: if item[0]:
real_count += write_to_db(fullname[1:]) real_count += write_to_db(fullname[1:])
else: else:
browse(fullname, interactive) browse(fullname, interactive)
log("%s: %d files (out of %d)" % (displaypath, real_count, count)) log(f"{displaypath}: {real_count} files (out of {count})")
################################################################################ ################################################################################
@ -489,7 +486,7 @@ Please make sure that:
if len(header) == 51: if len(header) == 51:
log("Using iTunesSD headers from existing database.") log("Using iTunesSD headers from existing database.")
if KnownEntries: log("Collected %d entries from existing database." % len(KnownEntries)) if KnownEntries: log(f"Collected {len(KnownEntries)} entries from existing database.")
else: else:
del header[18:] del header[18:]
if len(header) == 18: log("Using iTunesSD main header from existing database.") if len(header) == 18: log("Using iTunesSD main header from existing database.")
@ -516,7 +513,7 @@ Please make sure that:
try: try:
for dir in dirs: for dir in dirs:
browse("./" + dir, args.interactive) browse("./" + dir, args.interactive)
log("%d playable files were found on your iPod." % total_count) log(f"{total_count} playable files were found on your iPod.")
log() log()
log("Fixing iTunesSD header.") log("Fixing iTunesSD header.")
iTunesSD_file.seek(0) iTunesSD_file.seek(0)