Use f-strings in many places in acme and certbot. (#9225)

This commit is contained in:
Mads Jensen 2022-03-03 16:12:34 +01:00 committed by GitHub
parent 5d493ca53c
commit 92de543fe7
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
13 changed files with 45 additions and 61 deletions

View file

@ -279,7 +279,7 @@ class DNS01(KeyAuthorizationChallenge):
:rtype: str
"""
return "{0}.{1}".format(self.LABEL, name)
return f"{self.LABEL}.{name}"
@ChallengeResponse.register

View file

@ -1142,8 +1142,7 @@ class ClientNetwork:
'response', response_ct)
if content_type == cls.JSON_CONTENT_TYPE and jobj is None:
raise errors.ClientError(
'Unexpected response Content-Type: {0}'.format(response_ct))
raise errors.ClientError(f'Unexpected response Content-Type: {response_ct}')
return response
@ -1196,7 +1195,7 @@ class ClientNetwork:
if m is None:
raise # pragma: no cover
host, path, _err_no, err_msg = m.groups()
raise ValueError("Requesting {0}{1}:{2}".format(host, path, err_msg))
raise ValueError(f"Requesting {host}{path}:{err_msg}")
# If the Content-Type is DER or an Accept header was sent in the
# request, the response may not be UTF-8 encoded. In this case, we

View file

@ -157,12 +157,11 @@ class _Constant(jose.JSONDeSerializable, Hashable):
@classmethod
def from_json(cls, jobj: str) -> '_Constant':
if jobj not in cls.POSSIBLE_NAMES: # pylint: disable=unsupported-membership-test
raise jose.DeserializationError(
'{0} not recognized'.format(cls.__name__))
raise jose.DeserializationError(f'{cls.__name__} not recognized')
return cls.POSSIBLE_NAMES[jobj]
def __repr__(self) -> str:
return '{0}({1})'.format(self.__class__.__name__, self.name)
return f'{self.__class__.__name__}({self.name})'
def __eq__(self, other: Any) -> bool:
return isinstance(other, type(self)) and other.name == self.name

View file

@ -65,4 +65,4 @@ def _safe_jobj_compliance(instance: Any, jobj_method: str,
jobj.pop(uncompliant_field, None)
return jobj
raise AttributeError('Method {0}() is not implemented.'.format(jobj_method)) # pragma: no cover
raise AttributeError(f'Method {jobj_method}() is not implemented.') # pragma: no cover

View file

@ -226,8 +226,7 @@ class AccountFileStorage(interfaces.AccountStorage):
else:
self._symlink_to_accounts_dir(prev_server_path, server_path)
return prev_loaded_account
raise errors.AccountNotFound(
"Account at %s does not exist" % account_dir_path)
raise errors.AccountNotFound(f"Account at {account_dir_path} does not exist")
try:
with open(self._regr_path(account_dir_path)) as regr_file:
@ -296,8 +295,7 @@ class AccountFileStorage(interfaces.AccountStorage):
"""
account_dir_path = self._account_dir_path(account_id)
if not os.path.isdir(account_dir_path):
raise errors.AccountNotFound(
"Account at %s does not exist" % account_dir_path)
raise errors.AccountNotFound(f"Account at {account_dir_path} does not exist")
# Step 1: Delete account specific links and the directory
self._delete_account_dir_for_server_path(account_id, self.config.server_path)

View file

@ -383,8 +383,7 @@ def challb_to_achall(challb: messages.ChallengeBody, account_key: josepy.JWK,
challb=challb, domain=domain, account_key=account_key)
elif isinstance(chall, challenges.DNS):
return achallenges.DNS(challb=challb, domain=domain)
raise errors.Error(
"Received unsupported challenge of type: {0}".format(chall.typ))
raise errors.Error(f"Received unsupported challenge of type: {chall.typ}")
def gen_challenge_path(challbs: List[messages.ChallengeBody],

View file

@ -285,7 +285,7 @@ def match_and_check_overlaps(cli_config: configuration.NamespaceConfig,
matched: List[str] = _search_lineages(cli_config, find_matches, [], acceptable_matches)
if not matched:
raise errors.Error("No match found for cert-path {0}!".format(cli_config.cert_path))
raise errors.Error(f"No match found for cert-path {cli_config.cert_path}!")
elif len(matched) > 1:
raise errors.OverlappingMatchFound()
return matched
@ -318,26 +318,19 @@ def human_readable_cert_info(config: configuration.NamespaceConfig, cert: storag
if diff.days == 1:
status = "VALID: 1 day"
elif diff.days < 1:
status = "VALID: {0} hour(s)".format(diff.seconds // 3600)
status = f"VALID: {diff.seconds // 3600} hour(s)"
else:
status = "VALID: {0} days".format(diff.days)
status = f"VALID: {diff.days} days"
valid_string = "{0} ({1})".format(cert.target_expiry, status)
serial = format(crypto_util.get_serial_from_cert(cert.cert_path), 'x')
certinfo.append(" Certificate Name: {}\n"
" Serial Number: {}\n"
" Key Type: {}\n"
" Domains: {}\n"
" Expiry Date: {}\n"
" Certificate Path: {}\n"
" Private Key Path: {}".format(
cert.lineagename,
serial,
cert.private_key_type,
" ".join(cert.names()),
valid_string,
cert.fullchain,
cert.privkey))
certinfo.append(f" Certificate Name: {cert.lineagename}\n"
f" Serial Number: {serial}\n"
f" Key Type: {cert.private_key_type}\n"
f' Domains: {" ".join(cert.names())}\n'
f" Expiry Date: {valid_string}\n"
f" Certificate Path: {cert.fullchain}\n"
f" Private Key Path: {cert.privkey}")
return "".join(certinfo)

View file

@ -271,9 +271,9 @@ def perform_registration(acme: acme_client.ClientV2, config: configuration.Names
except messages.Error as e:
if e.code in ("invalidEmail", "invalidContact"):
if config.noninteractive_mode:
msg = ("The ACME server believes %s is an invalid email address. "
msg = (f"The ACME server believes {config.email} is an invalid email address. "
"Please ensure it is a valid email and attempt "
"registration again." % config.email)
"registration again.")
raise errors.Error(msg)
config.email = display_ops.get_email(invalid=True)
return perform_registration(acme, config, tos_cb)

View file

@ -356,16 +356,15 @@ class FileDisplay:
"""
# Can take either tuples or single items in choices list
if choices and isinstance(choices[0], tuple):
choices = ["%s - %s" % (c[0], c[1]) for c in choices]
choices = [f"{c[0]} - {c[1]}" for c in choices]
# Write out the message to the user
self.outfile.write(
"{new}{msg}{new}".format(new=os.linesep, msg=message))
self.outfile.write(f"{os.linesep}{message}{os.linesep}")
self.outfile.write(SIDE_FRAME + os.linesep)
# Write out the menu choices
for i, desc in enumerate(choices, 1):
msg = "{num}: {desc}".format(num=i, desc=desc)
msg = f"{i}: {desc}"
self.outfile.write(util.wrap_lines(msg))
# Keep this outside of the textwrap

View file

@ -52,10 +52,11 @@ def validate_hook(shell_cmd: str, hook_name: str) -> None:
if not _prog(cmd):
path = os.environ["PATH"]
if os.path.exists(cmd):
msg = "{1}-hook command {0} exists, but is not executable.".format(cmd, hook_name)
msg = f"{cmd}-hook command {hook_name} exists, but is not executable."
else:
msg = "Unable to find {2}-hook command {0} in the PATH.\n(PATH is {1})".format(
cmd, path, hook_name)
msg = (
f"Unable to find {hook_name}-hook command {cmd} in the PATH.\n(PATH is {path})"
)
raise errors.HookCommandNotFound(msg)

View file

@ -247,8 +247,7 @@ def _restore_bool(name: str, value: str) -> bool:
"""
lowercase_value = value.lower()
if lowercase_value not in ("true", "false"):
raise errors.Error(
"Expected True or False for {0} but found {1}".format(name, value))
raise errors.Error(f"Expected True or False for {name} but found {value}")
return lowercase_value == "true"
@ -271,7 +270,7 @@ def _restore_int(name: str, value: str) -> int:
try:
return int(value)
except ValueError:
raise errors.Error("Expected a numeric value for {0}".format(name))
raise errors.Error(f"Expected a numeric value for {name}")
def _restore_str(name: str, value: str) -> Optional[str]:
@ -323,8 +322,8 @@ def _avoid_invalidating_lineage(config: configuration.NamespaceConfig,
names = ", ".join(lineage.names())
raise errors.Error(
"You've asked to renew/replace a seemingly valid certificate with "
"a test certificate (domains: {0}). We will not do that "
"unless you use the --break-my-certs flag!".format(names))
f"a test certificate (domains: {names}). We will not do that "
"unless you use the --break-my-certs flag!")
def renew_cert(config: configuration.NamespaceConfig, domains: Optional[List[str]],
@ -375,7 +374,7 @@ def _renew_describe_results(config: configuration.NamespaceConfig, renew_success
notify = display_util.notify
notify_error = logger.error
notify('\n{}'.format(display_obj.SIDE_FRAME))
notify(f'\n{display_obj.SIDE_FRAME}')
renewal_noun = "simulated renewal" if config.dry_run else "renewal"
@ -383,19 +382,19 @@ def _renew_describe_results(config: configuration.NamespaceConfig, renew_success
notify("The following certificates are not due for renewal yet:")
notify(report(renew_skipped, "skipped"))
if not renew_successes and not renew_failures:
notify("No {renewal}s were attempted.".format(renewal=renewal_noun))
notify(f"No {renewal_noun}s were attempted.")
if (config.pre_hook is not None or
config.renew_hook is not None or config.post_hook is not None):
notify("No hooks were run.")
elif renew_successes and not renew_failures:
notify("Congratulations, all {renewal}s succeeded: ".format(renewal=renewal_noun))
notify(f"Congratulations, all {renewal_noun}s succeeded: ")
notify(report(renew_successes, "success"))
elif renew_failures and not renew_successes:
notify_error("All %ss failed. The following certificates could "
"not be renewed:", renewal_noun)
notify_error(report(renew_failures, "failure"))
elif renew_failures and renew_successes:
notify("The following {renewal}s succeeded:".format(renewal=renewal_noun))
notify(f"The following {renewal_noun}s succeeded:")
notify(report(renew_successes, "success") + "\n")
notify_error("The following %ss failed:", renewal_noun)
notify_error(report(renew_failures, "failure"))
@ -508,8 +507,8 @@ def handle_renewal_request(config: configuration.NamespaceConfig) -> None:
renew_skipped, parse_failures)
if renew_failures or parse_failures:
raise errors.Error("{0} renew failure(s), {1} parse failure(s)".format(
len(renew_failures), len(parse_failures)))
raise errors.Error(
f"{len(renew_failures)} renew failure(s), {len(parse_failures)} parse failure(s)")
# Windows installer integration tests rely on handle_renewal_request behavior here.
# If the text below changes, these tests will need to be updated accordingly.
@ -526,4 +525,4 @@ def _update_renewal_params_from_key(key_path: str, config: configuration.Namespa
config.key_type = 'ecdsa'
config.elliptic_curve = key.curve.name
else:
raise errors.Error('Key at {0} is of an unsupported type: {1}.'.format(key_path, type(key)))
raise errors.Error(f'Key at {key_path} is of an unsupported type: {type(key)}.')

View file

@ -60,10 +60,10 @@ def renewal_conf_files(config: configuration.NamespaceConfig) -> List[str]:
def renewal_file_for_certname(config: configuration.NamespaceConfig, certname: str) -> str:
"""Return /path/to/certname.conf in the renewal conf directory"""
path = os.path.join(config.renewal_configs_dir, "{0}.conf".format(certname))
path = os.path.join(config.renewal_configs_dir, f"{certname}.conf")
if not os.path.exists(path):
raise errors.CertStorageError("No certificate found with name {0} (expected "
"{1}).".format(certname, path))
raise errors.CertStorageError(
f"No certificate found with name {certname} (expected {path}).")
return path
@ -1179,7 +1179,7 @@ class RenewableCert(interfaces.RenewableCert):
if os.path.islink(old_privkey):
old_privkey = filesystem.readlink(old_privkey)
else:
old_privkey = "privkey{0}.pem".format(prior_version)
old_privkey = f"privkey{prior_version}.pem"
logger.debug("Writing symlink to old private key, %s.", old_privkey)
os.symlink(old_privkey, target["privkey"])
else:

View file

@ -241,8 +241,7 @@ class Reverter:
except (IOError, OSError):
# This file is required in all checkpoints.
logger.error("Unable to recover files from %s", cp_dir)
raise errors.ReverterError(
"Unable to recover files from %s" % cp_dir)
raise errors.ReverterError(f"Unable to recover files from {cp_dir}")
# Remove any newly added files if they exist
self._remove_contained_files(os.path.join(cp_dir, "NEW_FILES"))
@ -295,9 +294,7 @@ class Reverter:
# Verify no save_file is in protected_files
for filename in protected_files:
if filename in save_files:
raise errors.ReverterError(
"Attempting to overwrite challenge "
"file - %s" % filename)
raise errors.ReverterError(f"Attempting to overwrite challenge file - {filename}")
def register_file_creation(self, temporary: bool, *files: str) -> None:
r"""Register the creation of all files during certbot execution.