Skip to content

Commit

Permalink
Using f-strings where possible.
Browse files Browse the repository at this point in the history
  • Loading branch information
martinhoyer committed Jun 15, 2023
1 parent 2d458aa commit 23ecd38
Show file tree
Hide file tree
Showing 6 changed files with 20 additions and 31 deletions.
4 changes: 2 additions & 2 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,10 +283,10 @@ def __getattr__(cls, name: str) -> 'Mock':
os.makedirs('stories', exist_ok=True)
os.makedirs('spec', exist_ok=True)
for area in areas:
with open('{}.rst'.format(area.lstrip('/')), 'w') as doc:
with open(f"{area.lstrip('/')}.rst", 'w') as doc:
# Anchor and title
doc.write(f'.. _{area}:\n\n')
doc.write('{}\n{}\n'.format(areas[area], '=' * len(areas[area])))
doc.write(f"{areas[area]}\n{'=' * len(areas[area])}\n")
# Included stories
for story in tree.stories(names=[area], whole=True):
if story.enabled:
Expand Down
2 changes: 1 addition & 1 deletion tmt/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -3010,7 +3010,7 @@ def go(self) -> None:
# Show summary, store run data
if not self.plans:
raise tmt.utils.GeneralError("No plans found.")
self.verbose('Found {}.'.format(listed(self.plans, 'plan')))
self.verbose(f"Found {listed(self.plans, 'plan')}.")
self.save()

# Iterate over plans
Expand Down
8 changes: 3 additions & 5 deletions tmt/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,8 +120,7 @@ def get_command( # type: ignore[override]
return None
if len(matches) == 1:
return click.Group.get_command(self, context, matches[0])
context.fail('Did you mean {}?'.format(
listed(sorted(matches), join='or')))
context.fail(f"Did you mean {listed(sorted(matches), join='or')}?")
return None


Expand Down Expand Up @@ -1209,7 +1208,7 @@ def headfoot(text: str) -> None:
headfoot(f'{round(100 * test_coverage / total)}%')
if docs:
headfoot(f'{round(100 * docs_coverage / total)}%')
headfoot('from {}'.format(listed(total, 'story')))
headfoot(f"from {listed(total, 'story')}")
echo()


Expand Down Expand Up @@ -1354,8 +1353,7 @@ def stories_id(
@option(
'-t', '--template', default='empty', metavar='TEMPLATE',
type=click.Choice(['empty', *tmt.templates.INIT_TEMPLATES]),
help='Template ({}).'.format(
listed(tmt.templates.INIT_TEMPLATES, join='or')))
help=f"Template ({listed(tmt.templates.INIT_TEMPLATES, join='or')}).")
@verbosity_options
@force_dry_options
def init(
Expand Down
12 changes: 4 additions & 8 deletions tmt/convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -455,8 +455,7 @@ def read(
with open(datafile_path, encoding='utf-8') as datafile_file:
datafile = datafile_file.read()
except OSError:
raise ConvertError("Unable to open '{}'.".format(
datafile_path))
raise ConvertError(f"Unable to open '{datafile_path}'.")
echo(f"found in '{datafile_path}'.")

# If testinfo.desc exists read it to preserve content and remove it
Expand Down Expand Up @@ -489,8 +488,7 @@ def read(
stdout=subprocess.DEVNULL)
except FileNotFoundError:
raise ConvertError(
"Install tmt-test-convert to "
"convert metadata from {}.".format(filename))
f"Install tmt-test-convert to convert metadata from {filename}.")
except subprocess.CalledProcessError:
raise ConvertError(
"Failed to convert metadata using 'make testinfo.desc'.")
Expand All @@ -500,8 +498,7 @@ def read(
with open(testinfo_path, encoding='utf-8') as testinfo_file:
testinfo = testinfo_file.read()
except OSError:
raise ConvertError("Unable to open '{}'.".format(
testinfo_path))
raise ConvertError(f"Unable to open '{testinfo_path}'.")

# restraint
if restraint_file:
Expand Down Expand Up @@ -967,8 +964,7 @@ def read_nitrate_case(
if testcase.tester:
# Full 'Name Surname <[email protected]>' form
if testcase.tester.name is not None:
data['contact'] = '{} <{}>'.format(
testcase.tester.name, testcase.tester.email)
data['contact'] = f'{testcase.tester.name} <{testcase.tester.email}>'
else:
if makefile_data is None or 'contact' not in makefile_data:
# Otherwise use just the email address
Expand Down
2 changes: 1 addition & 1 deletion tmt/steps/provision/testcloud.py
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,7 @@ def prepare_ssh_key(self, key_type: Optional[str] = None) -> None:
# Generate new ssh key pair
else:
self.debug('Generating an ssh key.')
key_name = "id_{}".format(key_type if key_type is not None else 'rsa')
key_name = f"id_{key_type if key_type is not None else 'rsa'}"
self.key = [self.workdir / key_name]
command = Command("ssh-keygen", "-f", str(self.key[0]), "-N", "")
if key_type is not None:
Expand Down
23 changes: 9 additions & 14 deletions tmt/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -1133,7 +1133,7 @@ def _check_or_create_workdir_root_with_perms() -> None:

# Generated unique id or fail, has to be atomic call
for id_bit in range(1, WORKDIR_MAX + 1):
directory = 'run-{}'.format(str(id_bit).rjust(3, '0'))
directory = f"run-{str(id_bit).rjust(3, '0')}"
workdir = workdir_root / directory
try:
# Call is atomic, no race possible
Expand Down Expand Up @@ -2534,7 +2534,7 @@ def format(
"""
indent_string = (indent + 1) * ' '
# Key
output = '{} '.format(str(key).rjust(indent, ' '))
output = f"{str(key).rjust(indent, ' ')} "
if key_color is not None:
output = style(output, fg=key_color)
# Bool
Expand Down Expand Up @@ -2593,8 +2593,7 @@ def create_directory(
path.mkdir(exist_ok=True, parents=True)
say(f"Directory '{path}' created.")
except OSError as error:
raise FileError("Failed to create {} '{}' ({})".format(
name, path, error)) from error
raise FileError(f"Failed to create {name} '{path}' ({error})") from error


def create_file(
Expand Down Expand Up @@ -2623,8 +2622,7 @@ def create_file(
say(f"{name.capitalize()} '{path}' {action}.")
path.chmod(mode)
except OSError as error:
raise FileError("Failed to create {} '{}' ({})".format(
name, path, error))
raise FileError(f"Failed to create {name} '{path}' ({error})")


# Avoid multiple subprocess calls for the same url
Expand Down Expand Up @@ -3327,16 +3325,14 @@ def _load(self, text: str) -> None:
"Unable to detect StructuredField version")
self.version(int(version_match.groups()[0]))
log.debug(
"Detected StructuredField version {}".format(
self.version()))
f"Detected StructuredField version {self.version()}")
# Convert to dictionary, remove escapes and save the order
keys = parts[1::2]
escape = re.compile(r"^\[structured-field-escape\]", re.MULTILINE)
values = [escape.sub("", value) for value in parts[2::2]]
for key, value in zip(keys, values):
self.set(key, value)
log.debug("Parsed sections:\n{}".format(
pprint.pformat(self._sections)))
log.debug(f"Parsed sections:\n{pprint.pformat(self._sections)}")

def _save_version_zero(self) -> str:
""" Save version 0 format """
Expand All @@ -3363,8 +3359,8 @@ def _save(self) -> str:
if self:
result.append(
"[structured-field-start]\n"
"This is StructuredField version {}. "
"Please, edit with care.\n".format(self._version))
f"This is StructuredField version {self._version}. "
"Please, edit with care.\n")
for section, content in self.iterate():
result.append("[{}]\n{}".format(section, escape.sub(
"[structured-field-escape]\\1", content)))
Expand Down Expand Up @@ -3492,8 +3488,7 @@ def get(
return self._read_section(content)[item]
except KeyError:
raise StructuredFieldError(
"Unable to read '{!r}' from section '{!r}'".format(
ascii(item), ascii(section)))
f"Unable to read '{ascii(item)!r}' from section '{ascii(section)!r}'")

def set(self, section: str, content: Any,
item: Optional[str] = None) -> None:
Expand Down

0 comments on commit 23ecd38

Please sign in to comment.