From 92de543fe739c7159ef10ce895c468ccc1c1f089 Mon Sep 17 00:00:00 2001 From: Mads Jensen Date: Thu, 3 Mar 2022 16:12:34 +0100 Subject: Use f-strings in many places in acme and certbot. (#9225) --- acme/acme/challenges.py | 2 +- acme/acme/client.py | 5 ++--- acme/acme/messages.py | 5 ++--- acme/acme/mixins.py | 2 +- certbot/certbot/_internal/account.py | 6 ++---- certbot/certbot/_internal/auth_handler.py | 3 +-- certbot/certbot/_internal/cert_manager.py | 27 ++++++++++----------------- certbot/certbot/_internal/client.py | 4 ++-- certbot/certbot/_internal/display/obj.py | 7 +++---- certbot/certbot/_internal/hooks.py | 7 ++++--- certbot/certbot/_internal/renewal.py | 23 +++++++++++------------ certbot/certbot/_internal/storage.py | 8 ++++---- certbot/certbot/reverter.py | 7 ++----- 13 files changed, 45 insertions(+), 61 deletions(-) diff --git a/acme/acme/challenges.py b/acme/acme/challenges.py index ce0cf2ed4..9000b370a 100644 --- a/acme/acme/challenges.py +++ b/acme/acme/challenges.py @@ -279,7 +279,7 @@ class DNS01(KeyAuthorizationChallenge): :rtype: str """ - return "{0}.{1}".format(self.LABEL, name) + return f"{self.LABEL}.{name}" @ChallengeResponse.register diff --git a/acme/acme/client.py b/acme/acme/client.py index aacbbc263..2e86ce549 100644 --- a/acme/acme/client.py +++ b/acme/acme/client.py @@ -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 diff --git a/acme/acme/messages.py b/acme/acme/messages.py index c9704d537..299da68d7 100644 --- a/acme/acme/messages.py +++ b/acme/acme/messages.py @@ -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 diff --git a/acme/acme/mixins.py b/acme/acme/mixins.py index 38551d550..e6e678d60 100644 --- a/acme/acme/mixins.py +++ b/acme/acme/mixins.py @@ -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 diff --git a/certbot/certbot/_internal/account.py b/certbot/certbot/_internal/account.py index 8c45efe21..6097ee038 100644 --- a/certbot/certbot/_internal/account.py +++ b/certbot/certbot/_internal/account.py @@ -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) diff --git a/certbot/certbot/_internal/auth_handler.py b/certbot/certbot/_internal/auth_handler.py index e7e059656..979ef0220 100644 --- a/certbot/certbot/_internal/auth_handler.py +++ b/certbot/certbot/_internal/auth_handler.py @@ -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], diff --git a/certbot/certbot/_internal/cert_manager.py b/certbot/certbot/_internal/cert_manager.py index 7eeddfa1a..c7205c304 100644 --- a/certbot/certbot/_internal/cert_manager.py +++ b/certbot/certbot/_internal/cert_manager.py @@ -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) diff --git a/certbot/certbot/_internal/client.py b/certbot/certbot/_internal/client.py index 9688918cd..057b4f059 100644 --- a/certbot/certbot/_internal/client.py +++ b/certbot/certbot/_internal/client.py @@ -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) diff --git a/certbot/certbot/_internal/display/obj.py b/certbot/certbot/_internal/display/obj.py index 39b737e80..c5c2e388b 100644 --- a/certbot/certbot/_internal/display/obj.py +++ b/certbot/certbot/_internal/display/obj.py @@ -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 diff --git a/certbot/certbot/_internal/hooks.py b/certbot/certbot/_internal/hooks.py index 813f7f6bd..76cda466a 100644 --- a/certbot/certbot/_internal/hooks.py +++ b/certbot/certbot/_internal/hooks.py @@ -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) diff --git a/certbot/certbot/_internal/renewal.py b/certbot/certbot/_internal/renewal.py index 91a38b11f..4fb2ca00a 100644 --- a/certbot/certbot/_internal/renewal.py +++ b/certbot/certbot/_internal/renewal.py @@ -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)}.') diff --git a/certbot/certbot/_internal/storage.py b/certbot/certbot/_internal/storage.py index 9bdbe2731..567073acf 100644 --- a/certbot/certbot/_internal/storage.py +++ b/certbot/certbot/_internal/storage.py @@ -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: diff --git a/certbot/certbot/reverter.py b/certbot/certbot/reverter.py index 69a8ac83f..0c22b3e49 100644 --- a/certbot/certbot/reverter.py +++ b/certbot/certbot/reverter.py @@ -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. -- cgit v1.2.3