Skip to content

Commit

Permalink
use f-strings
Browse files Browse the repository at this point in the history
  • Loading branch information
giampaolo committed Jul 2, 2024
1 parent de2ea47 commit 9285f93
Show file tree
Hide file tree
Showing 22 changed files with 280 additions and 296 deletions.
6 changes: 3 additions & 3 deletions demo/anti_flood_ftpd.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,8 @@ def process_command(self, *args, **kwargs):
def ban(self, ip):
# ban ip and schedule next un-ban
if ip not in self.banned_ips:
self.log('banned IP %s for command flooding' % ip)
self.respond('550 You are banned for %s seconds.' % self.ban_for)
self.log(f'banned IP {ip} for command flooding')
self.respond(f'550 You are banned for {self.ban_for} seconds.')
self.close()
self.banned_ips.append(ip)

Expand All @@ -63,7 +63,7 @@ def unban(self, ip):
except ValueError:
pass
else:
self.log('unbanning IP %s' % ip)
self.log(f'unbanning IP {ip}')

def close(self):
FTPHandler.close(self)
Expand Down
10 changes: 5 additions & 5 deletions demo/unix_daemon.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,12 +87,12 @@ def stop():
try:
os.kill(pid, sig)
except ProcessLookupError:
print("\nstopped (pid %s)" % pid)
print(f"\nstopped (pid {pid})")
i += 1
if i == 25:
sig = signal.SIGKILL
elif i == 50:
sys.exit("\ncould not kill daemon (pid %s)" % pid)
sys.exit(f"\ncould not kill daemon (pid {pid})")
time.sleep(0.1)


Expand All @@ -102,7 +102,7 @@ def status():
if not pid or not pid_exists(pid):
print("daemon not running")
else:
print("daemon running with pid %s" % pid)
print(f"daemon running with pid {pid}")
sys.exit(0)


Expand Down Expand Up @@ -148,12 +148,12 @@ def _daemonize():
# write pidfile
pid = str(os.getpid())
with open(PID_FILE, 'w') as f:
f.write("%s\n" % pid)
f.write(f"{pid}\n")
atexit.register(lambda: os.remove(PID_FILE))

pid = get_pid()
if pid and pid_exists(pid):
sys.exit('daemon already running (pid %s)' % pid)
sys.exit(f'daemon already running (pid {pid})')
# instance FTPd before daemonizing, so that in case of problems we
# get an exception here and exit immediately
server = get_server()
Expand Down
4 changes: 2 additions & 2 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ def get_version():

# General information about the project.
project = PROJECT_NAME
copyright = '2009-%s, %s' % (THIS_YEAR, AUTHOR)
copyright = f'2009-{THIS_YEAR}, {AUTHOR}'
author = AUTHOR

# The version info for the project you're documenting, acts as replacement for
Expand Down Expand Up @@ -269,7 +269,7 @@ def get_version():
# html_search_scorer = 'scorer.js'

# Output file base name for HTML help builder.
htmlhelp_basename = '%s-doc' % PROJECT_NAME
htmlhelp_basename = f'{PROJECT_NAME}-doc'

# -- Options for LaTeX output ---------------------------------------------

Expand Down
2 changes: 1 addition & 1 deletion pyftpdlib/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ def main(args=None):

options = parser.parse_args(args=args)
if options.version:
sys.exit("pyftpdlib %s" % __ver__)
sys.exit(f"pyftpdlib {__ver__}")
if options.debug:
config_logging(level=logging.DEBUG)

Expand Down
18 changes: 9 additions & 9 deletions pyftpdlib/_asyncore.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ def _strerror(err):
except (ValueError, OverflowError, NameError):
if err in errorcode:
return errorcode[err]
return "Unknown error %s" % err
return f"Unknown error {err}"


_reraised_exceptions = (KeyboardInterrupt, SystemExit)
Expand Down Expand Up @@ -244,7 +244,7 @@ def __repr__(self):
status.append('%s:%d' % self.addr)
except TypeError:
status.append(repr(self.addr))
return '<%s at %#x>' % (' '.join(status), id(self))
return '<%s at %#x>' % (' '.join(status), id(self)) # noqa

def add_channel(self, map=None):
# self.log_info('adding channel %s' % self)
Expand Down Expand Up @@ -369,11 +369,11 @@ def close(self):
raise

def log(self, message):
sys.stderr.write('log: %s\n' % str(message))
sys.stderr.write(f'log: {str(message)}\n')

def log_info(self, message, type='info'):
if type not in self.ignore_log_types:
print('%s: %s' % (type, message)) # noqa
print(f'{type}: {message}') # noqa

def handle_read_event(self):
if self.accepting:
Expand Down Expand Up @@ -415,10 +415,10 @@ def handle_error(self):
try:
self_repr = repr(self)
except Exception:
self_repr = '<__repr__(self) failed for object at %0x>' % id(self)
self_repr = f'<__repr__(self) failed for object at {id(self):0x}>'

self.log_info(
'uncaptured python exception, closing channel %s (%s:%s %s)'
'uncaptured python exception, closing channel %s (%s:%s %s)' # noqa
% (self_repr, t, v, tbinfo),
'error',
)
Expand Down Expand Up @@ -469,7 +469,7 @@ def writable(self):

def send(self, data):
if self.debug:
self.log_info('sending %s' % repr(data))
self.log_info(f'sending {repr(data)}')
self.out_buffer = self.out_buffer + data
self.initiate_send()

Expand Down Expand Up @@ -498,7 +498,7 @@ def compact_traceback():
del tb

file, function, line = tbinfo[-1]
info = ' '.join(['[%s|%s|%s]' % x for x in tbinfo])
info = ' '.join(['[%s|%s|%s]' % x for x in tbinfo]) # noqa: UP031
return (file, function, line), t, v, info


Expand Down Expand Up @@ -534,7 +534,7 @@ def __init__(self, fd):
def __del__(self):
if self.fd >= 0:
warnings.warn(
"unclosed file %r" % self,
f"unclosed file {self!r}",
ResourceWarning,
source=self,
stacklevel=2,
Expand Down
26 changes: 13 additions & 13 deletions pyftpdlib/authorizers.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,9 +104,9 @@ def add_user(
provide customized response strings when user log-in and quit.
"""
if self.has_user(username):
raise ValueError('user %r already exists' % username)
raise ValueError(f'user {username!r} already exists')
if not os.path.isdir(homedir):
raise ValueError('no such directory: %r' % homedir)
raise ValueError(f'no such directory: {homedir!r}')
homedir = os.path.realpath(homedir)
self._check_permissions(username, perm)
dic = {
Expand Down Expand Up @@ -145,7 +145,7 @@ def override_perm(self, username, directory, perm, recursive=False):
"""Override permissions for a given directory."""
self._check_permissions(username, perm)
if not os.path.isdir(directory):
raise ValueError('no such directory: %r' % directory)
raise ValueError(f'no such directory: {directory!r}')
directory = os.path.normcase(os.path.realpath(directory))
home = os.path.normcase(self.get_home_dir(username))
if directory == home:
Expand Down Expand Up @@ -242,7 +242,7 @@ def _check_permissions(self, username, perm):
warned = 0
for p in perm:
if p not in self.read_perms + self.write_perms:
raise ValueError('no such permission %r' % p)
raise ValueError(f'no such permission {p!r}')
if (
username == 'anonymous'
and p in self.write_perms
Expand Down Expand Up @@ -305,15 +305,15 @@ def __init__(self):
if user == 'anonymous':
raise AuthorizerError('invalid username "anonymous"')
if user not in users:
raise AuthorizerError('unknown user %s' % user)
raise AuthorizerError(f'unknown user {user}')

if self.anonymous_user is not None:
if not self.has_user(self.anonymous_user):
raise AuthorizerError('no such user %s' % self.anonymous_user)
raise AuthorizerError(f'no such user {self.anonymous_user}')
home = self.get_home_dir(self.anonymous_user)
if not os.path.isdir(home):
raise AuthorizerError(
'no valid home set for user %s' % self.anonymous_user
f'no valid home set for user {self.anonymous_user}'
)

def override_user(
Expand All @@ -339,13 +339,13 @@ def override_user(
"at least one keyword argument must be specified"
)
if self.allowed_users and username not in self.allowed_users:
raise AuthorizerError('%s is not an allowed user' % username)
raise AuthorizerError(f'{username} is not an allowed user')
if self.rejected_users and username in self.rejected_users:
raise AuthorizerError('%s is not an allowed user' % username)
raise AuthorizerError(f'{username} is not an allowed user')
if username == "anonymous" and password:
raise AuthorizerError("can't assign password to anonymous user")
if not self.has_user(username):
raise AuthorizerError('no such user %s' % username)
raise AuthorizerError(f'no such user {username}')

if username in self._dummy_authorizer.user_table:
# re-set parameters
Expand Down Expand Up @@ -426,7 +426,7 @@ def __init__(self, anonymous_user=None):
try:
pwd.getpwnam(self.anonymous_user).pw_dir # noqa
except KeyError:
raise AuthorizerError('no such user %s' % anonymous_user)
raise AuthorizerError(f'no such user {anonymous_user}')

# --- overridden / private API

Expand Down Expand Up @@ -586,7 +586,7 @@ def __init__(
for username in self.allowed_users:
if not self._has_valid_shell(username):
raise AuthorizerError(
"user %s has not a valid shell" % username
f"user {username} has not a valid shell"
)

def override_user(
Expand Down Expand Up @@ -757,7 +757,7 @@ def get_home_dir(self, username):
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path)
except OSError:
raise AuthorizerError(
"No profile directory defined for user %s" % username
f"No profile directory defined for user {username}"
)
value = winreg.QueryValueEx(key, "ProfileImagePath")[0]
home = win32api.ExpandEnvironmentStrings(value)
Expand Down
10 changes: 5 additions & 5 deletions pyftpdlib/filesystems.py
Original file line number Diff line number Diff line change
Expand Up @@ -441,7 +441,7 @@ def get_group_by_gid(gid):
# https://github.com/giampaolo/pyftpdlib/issues/187
fmtstr = '%d %Y' if now - st.st_mtime > SIX_MONTHS else '%d %H:%M'
try:
mtimestr = "%s %s" % (
mtimestr = "%s %s" % ( # noqa: UP031
_months_map[mtime.tm_mon],
time.strftime(fmtstr, mtime),
)
Expand All @@ -450,7 +450,7 @@ def get_group_by_gid(gid):
# old (prior to year 1900) in which case we return
# the current time as last mtime.
mtime = timefunc()
mtimestr = "%s %s" % (
mtimestr = "%s %s" % ( # noqa: UP031
_months_map[mtime.tm_mon],
time.strftime("%d %H:%M", mtime),
)
Expand Down Expand Up @@ -590,13 +590,13 @@ def format_mlsx(self, basedir, listing, perms, facts, ignore_err=True):
# platforms should use some platform-specific method (e.g.
# on Windows NTFS filesystems MTF records could be used).
if show_unique:
retfacts['unique'] = "%xg%x" % (st.st_dev, st.st_ino)
retfacts['unique'] = f"{st.st_dev:x}g{st.st_ino:x}"

# facts can be in any order but we sort them by name
factstring = "".join(
["%s=%s;" % (x, retfacts[x]) for x in sorted(retfacts.keys())]
[f"{x}={retfacts[x]};" for x in sorted(retfacts.keys())]
)
line = "%s %s\r\n" % (factstring, basename)
line = f"{factstring} {basename}\r\n"
yield line.encode('utf8', self.cmd_channel.unicode_errors)


Expand Down
Loading

0 comments on commit 9285f93

Please sign in to comment.