Skip to content

Commit

Permalink
[global] Replace use of .format() with f-strings
Browse files Browse the repository at this point in the history
As part of the project's effort to modernize on f-strings, this commit
replaces all usage of .format() with f-string equivalents. The vast
majority of these are in-place syntax changes, but a limited number
change the order of list items or some formatting tricks in order to
appease PEP8.

None of these conversions change the underlying logic of the flows they
appear in.

Related: sosreport#3472 discussion

Signed-off-by: Jake Hunsaker <jacob.r.hunsaker@gmail.com>
  • Loading branch information
TurboTurtle authored and arif-ali committed Feb 22, 2024
1 parent 9090280 commit 57d2134
Show file tree
Hide file tree
Showing 34 changed files with 143 additions and 180 deletions.
4 changes: 1 addition & 3 deletions sos/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,9 +90,7 @@ def __init__(self, args):
aliases.insert(0, com)
_com = ', '.join(aliases)
desc = self._components[com][0].desc
_com_string += (
"\t{com:<30}{desc}\n".format(com=_com, desc=desc)
)
_com_string += (f"\t{_com:<30}{desc}\n")
usage_string = ("%(prog)s <component> [options]\n\n"
"Available components:\n")
usage_string = usage_string + _com_string
Expand Down
2 changes: 1 addition & 1 deletion sos/cleaner/archives/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ def get_archive_root(self):

def report_msg(self, msg):
"""Helper to easily format ui messages on a per-report basis"""
self.ui_log.info("{:<50} {}".format(self.ui_name + ' :', msg))
self.ui_log.info(f"{self.ui_name + ' :':<50} {msg}")

def _fmt_log_msg(self, msg):
return "[cleaner:%s] %s" % (self.archive_name, msg)
Expand Down
30 changes: 13 additions & 17 deletions sos/collector/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -516,7 +516,7 @@ def display_help(cls, section):
)
for hsec in hsections:
section.add_text(
"{:>8}{:<40}{:<30}".format(' ', bold(hsec), hsections[hsec]),
f"{' ':>8}{bold(hsec):<40}{hsections[hsec]:<30}",
newline=False
)

Expand Down Expand Up @@ -650,9 +650,9 @@ def list_options(self):
sys.stdout.write('Use the short name with --cluster-type or cluster '
'options (-c)\n\n')
for cluster in sorted(self.clusters):
sys.stdout.write(" {:<15} {:30}\n".format(
cluster,
self.clusters[cluster].cluster_name))
sys.stdout.write(
f" {cluster:<15} {self.clusters[cluster].cluster_name:30}\n"
)

_opts = {}
for _cluster in self.clusters:
Expand All @@ -665,22 +665,18 @@ def list_options(self):
_opts[opt.name].cluster.append(clust)

sys.stdout.write('\nThe following cluster options are available:\n\n')
sys.stdout.write(' {:25} {:15} {:<10} {:10} {:<}\n'.format(
'Cluster',
'Option Name',
'Type',
'Default',
'Description'
))
sys.stdout.write(
f" {'Cluster':25} {'Option Name':15} {'Type':<10} {'Default':10} "
f"{'Description':<}\n"
)

for _opt in sorted(_opts, key=lambda x: _opts[x].cluster):
opt = _opts[_opt]
optln = ' {:25} {:15} {:<10} {:<10} {:<10}\n'.format(
', '.join(c for c in sorted(opt.cluster)),
opt.name,
opt.opt_type.__name__,
str(opt.value),
opt.description)
optln = (
f" {', '.join(c for c in sorted(opt.cluster)):25} "
f"{opt.name:15} {opt.opt_type.__name__:<10} "
f"{str(opt.value):<10} {opt.description:<10}\n"
)
sys.stdout.write(optln)
sys.stdout.write('\nOptions take the form of cluster.name=value'
'\nE.G. "ovirt.no-database=True" or '
Expand Down
16 changes: 8 additions & 8 deletions sos/collector/clusters/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,10 +145,11 @@ def display_help(cls, section):
"These options may be toggled or changed using '%s'"
% bold("-c %s.$option=$value" % cls.__name__)
)
optsec.add_text(bold(
"\n{:<4}{:<20}{:<30}{:<20}\n".format(
' ', "Option Name", "Default", "Description")
), newline=False
optsec.add_text(
bold(
f"\n{' ':<4}{'Option Name':<20}{'Default':<30}"
f"{'Description':<20}\n"),
newline=False
)
for opt in cls.option_list:
val = opt[1]
Expand All @@ -157,8 +158,7 @@ def display_help(cls, section):
val = 'True/On'
else:
val = 'False/Off'
_ln = "{:<4}{:<20}{:<30}{:<20}".format(' ', opt[0], val,
opt[2])
_ln = f"{' ':<4}{opt[0]:<20}{val:<30}{opt[2]:<20}"
optsec.add_text(_ln, newline=False)

@classmethod
Expand All @@ -185,13 +185,13 @@ def display_self_help(cls, section):
'The following cluster profiles are locally available:\n'
)
section.add_text(
"{:>8}{:<40}{:<30}".format(' ', 'Name', 'Description'),
f"{' ':>8}{'Name':<40}{'Description':<30}",
newline=False
)
for cluster in clusters:
_sec = bold("collect.clusters.%s" % cluster[0])
section.add_text(
"{:>8}{:<40}{:<30}".format(' ', _sec, cluster[1].cluster_name),
f"{' ':>8}{_sec:<40}{cluster[1].cluster_name:<30}",
newline=False
)

Expand Down
24 changes: 11 additions & 13 deletions sos/collector/clusters/ovirt.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,20 +153,18 @@ def parse_db_conf(self):
return False

def collect_database(self):
plugin = 'postgresql'
sos_opt = (
'-k {plugin}.dbname={db} '
'-k {plugin}.dbhost={dbhost} '
'-k {plugin}.dbport={dbport} '
'-k {plugin}.username={dbuser} '
).format(plugin='postgresql',
db=self.conf['ENGINE_DB_DATABASE'],
dbhost=self.conf['ENGINE_DB_HOST'],
dbport=self.conf['ENGINE_DB_PORT'],
dbuser=self.conf['ENGINE_DB_USER']
)
cmd = ('PGPASSWORD={} /usr/sbin/sosreport --name=postgresql '
'--batch -o postgresql {}'
).format(self.conf['ENGINE_DB_PASSWORD'], sos_opt)
f"-k {plugin}.dbname={self.conf['ENGINE_DB_DATABASE']} "
f"-k {plugin}.dbhost={self.conf['ENGINE_DB_HOST']} "
f"-k {plugin}.dbport={self.conf['ENGINE_DB_PORT']} "
f"-k {plugin}.dbuser={self.conf['ENGINE_DB_USER']}"
)

cmd = (
f"PGPASSWORD={self.conf['ENGINE_DB_PASSWORD']} /usr/sbin/sos "
f"report --name=postgresql --batch -o postgresql {sos_opt}"
)
db_sos = self.exec_primary_cmd(cmd, need_root=True)
for line in db_sos['output'].splitlines():
if fnmatch.fnmatch(line, '*sosreport-*tar*'):
Expand Down
6 changes: 4 additions & 2 deletions sos/collector/clusters/saltstack.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,14 +46,16 @@ def _parse_manage_status(self, output: str) -> list:

def _get_hostnames_from_grain(self, manage_status: dict) -> list:
hostnames = []
fqdn_cmd = "salt --out=newline_values_only {minion} grains.get fqdn"
for status, minions in manage_status.items():
if status == "down":
self.log_warn(f"Node(s) {minions} are status down.")
hostnames.extend(minions)
else:
for minion in minions:
node_cmd = fqdn_cmd.format(minion=minion)
node_cmd = (
f"salt --out=newline_values_only {minion} "
f"grains.get fqdn"
)
hostnames.append(
self.exec_primary_cmd(node_cmd)["output"].strip()
)
Expand Down
2 changes: 1 addition & 1 deletion sos/collector/sosnode.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ def _load_remote_transport(self, commons):
return SSHControlPersist(self.address, commons)

def _fmt_msg(self, msg):
return '{:<{}} : {}'.format(self._hostname, self.hostlen + 1, msg)
return f"{self._hostname:<{self.hostlen + 1}} : {msg}"

@property
def env_vars(self):
Expand Down
2 changes: 1 addition & 1 deletion sos/collector/transports/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ def display_self_help(cls, section):
_sec = bold("collect.transports.%s" % transport)
_desc = "The '%s' transport" % transport.lower()
section.add_text(
"{:>8}{:<45}{:<30}".format(' ', _sec, _desc),
f"{' ':>8}{_sec:<45}{_desc:<30}",
newline=False
)

Expand Down
2 changes: 1 addition & 1 deletion sos/help/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ def display_self_help(self):

for sect in sections:
avail_help.add_text(
"\t{:<36}{}".format(bold(sect), sections[sect]),
f"\t{bold(sect):<36}{sections[sect]}",
newline=False
)

Expand Down
24 changes: 9 additions & 15 deletions sos/policies/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,24 +242,17 @@ def get_archive_name(self):
rand = ''.join(random.choice(string.ascii_lowercase) for x in range(7))

if self.name_pattern == 'legacy':
nstr = "sosreport-{name}{case}{date}"
case = '.' + case if case else ''
date = '-%Y%m%d%H%M%S'
nstr = f"sosreport-{name}{case}{date}"
elif self.name_pattern == 'friendly':
nstr = "sosreport-{name}{label}{case}{date}-{rand}"
case = '-' + case if case else ''
label = '-' + label if label else ''
date = '-%Y-%m-%d'
nstr = f"sosreport-{name}{label}{case}{date}-{rand}"
else:
nstr = self.name_pattern

nstr = nstr.format(
name=name,
label=label,
case=case,
date=date,
rand=rand
)
return self.sanitize_filename(time.strftime(nstr))

# for some specific binaries like "xz", we need to determine package
Expand Down Expand Up @@ -409,8 +402,10 @@ def display_help(self, section):
"For more information on distribution policies, see below\n"
)
for pol in pols:
seealso.add_text("{:>8}{:<20}{:<30}".format(' ', pol, pols[pol]),
newline=False)
seealso.add_text(
f"{' ':>8}{pol:<20}{pols[pol]:<30}",
newline=False
)

def display_results(self, archive, directory, checksum, archivestat=None,
map_file=None):
Expand Down Expand Up @@ -501,10 +496,9 @@ def _fmt_vendor_urls(self):
:rtype: ``str``
"""
width = max([len(v[0]) for v in self.vendor_urls])
return "\n".join("\t{desc:<{width}} : {url}".format(
desc=u[0], width=width, url=u[1])
for u in self.vendor_urls
)
return "\n".join(
f"\t{url[0]:<{width}} : {url[1]}" for url in self.vendor_urls
)

def register_presets(self, presets, replace=False):
"""Add new presets to this policy object.
Expand Down
14 changes: 4 additions & 10 deletions sos/policies/distros/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -199,27 +199,21 @@ def display_distro_help(cls, section):

refsec = section.add_section('Reference URLs')
for url in cls.vendor_urls:
refsec.add_text(
"{:>8}{:<30}{:<40}".format(' ', url[0], url[1]),
newline=False
)
refsec.add_text(f"{' ':>8}{url[0]:<30}{url[1]:<40}", newline=False)

presec = section.add_section('Presets Available With This Policy\n')
presec.add_text(
bold(
"{:>8}{:<20}{:<45}{:<30}".format(' ', 'Preset Name',
'Description',
'Enabled Options')
f"{' ':>8}{'Preset Name':<20}{'Description':<45}"
f"{'Enabled Options':<30}"
),
newline=False
)
for preset in _pol.presets:
_preset = _pol.presets[preset]
_opts = ' '.join(_preset.opts.to_args())
presec.add_text(
"{:>8}{:<20}{:<45}{:<30}".format(
' ', preset, _preset.desc, _opts
),
f"{' ':>8}{preset:<20}{_preset.desc:<45}{_opts:<30}",
newline=False
)

Expand Down
24 changes: 13 additions & 11 deletions sos/policies/distros/redhat.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ def display_distro_help(cls, section):
for subc in subs:
subln = bold("policies.%s" % subc)
section.add_text(
"{:>8}{:<35}{:<30}".format(' ', subln, subs[subc].distro),
f"{' ':>8}{subln:<35}{subs[subc].distro:<30}",
newline=False
)

Expand Down Expand Up @@ -563,18 +563,20 @@ def probe_preset(self):
return self.find_preset(RHOCP)

def create_sos_container(self, image=None, auth=None, force_pull=False):
_cmd = ("{runtime} run -di --name {name} --privileged --ipc=host"
" --net=host --pid=host -e HOST=/host -e NAME={name} -e "
"IMAGE={image} {pull} -v /run:/run -v /var/log:/var/log -v "
"/etc/machine-id:/etc/machine-id -v "
"/etc/localtime:/etc/localtime -v /:/host {auth} {image}")
_image = image or self.container_image
_pull = '--pull=always' if force_pull else ''
return _cmd.format(runtime=self.container_runtime,
name=self.sos_container_name,
image=_image,
pull=_pull,
auth=auth or '')
return (
f"{self.container_runtime} run -di "
f"--name {self.sos_container_name} --privileged --ipc=host "
f"--net=host --pid=host -e HOST=/host "
f"-e NAME={self.sos_container_name} -e "
f"IMAGE={_image} {_pull} "
f"-v /run:/run -v /var/log:/var/log "
f"-v /etc/machine-id:/etc/machine-id "
f"-v /etc/localtime:/etc/localtime "
f"-v /:/host "
f"{auth or ''} {_image}"
)

def set_cleanup_cmd(self):
return 'podman rm --force %s' % self.sos_container_name
Expand Down
5 changes: 2 additions & 3 deletions sos/report/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def _format_since(date):
didn't. It's used in the _get_parser.
This will also be a good place to add human readable and relative
date parsing (like '2 days ago') in the future """
return datetime.strptime('{:<014s}'.format(date), '%Y%m%d%H%M%S')
return datetime.strptime(f"{date:<014s}", '%Y%m%d%H%M%S')


# valid modes for --chroot
Expand Down Expand Up @@ -432,8 +432,7 @@ def display_help(cls, section):
}
helpln = ''
for ln in help_lines:
ssec.add_text("\t{:<36}{}".format(ln, help_lines[ln]),
newline=False)
ssec.add_text(f"\t{ln:<36}{help_lines[ln]}", newline=False)
ssec.add_text(helpln)

def print_header(self):
Expand Down
13 changes: 6 additions & 7 deletions sos/report/plugins/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -844,10 +844,10 @@ def display_plugin_help(cls, section):
"These options may be toggled or changed using '%s'"
% bold("-k %s.option_name=$value" % cls.plugin_name)
)
optsec.add_text(bold(
"\n{:<4}{:<20}{:<30}{:<20}\n".format(
' ', "Option Name", "Default", "Description")
), newline=False
optsec.add_text(
bold((f"\n{' ':<4}{'Option Name':<20}{'Default':<30}"
f"{'Description':<20}")),
newline=False
)

opt_indent = ' ' * 54
Expand All @@ -861,8 +861,7 @@ def display_plugin_help(cls, section):
_def = "True/On"
else:
_def = "False/Off"
_ln = "{:<4}{:<20}{:<30}{:<20}".format(' ', opt.name, _def,
opt.desc)
_ln = f"{' ':<4}{opt.name:<20}{_def:<30}{opt.desc:<20}"
optsec.add_text(
textwrap.fill(_ln, width=TERMSIZE,
subsequent_indent=opt_indent),
Expand Down Expand Up @@ -932,7 +931,7 @@ def display_self_help(cls, section):
seealso.add_text(
"Additional relevant information may be available in these "
"help sections:\n\n%s" % "\n".join(
"{:>8}{:<30}{:<30}".format(' ', sec, desc)
f"{' ':>8}{sec:<30}{desc:<30}"
for sec, desc in _also.items()
), newline=False
)
Expand Down
2 changes: 1 addition & 1 deletion sos/report/plugins/apt.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def setup(self):
pkg_list = ' '.join(
[v.split('\t')[0] for v in dpkg_output if 'ok installed' in v])
self.add_cmd_output(
"apt-cache policy {}".format(pkg_list),
f"apt-cache policy {pkg_list}",
suggest_filename="apt-cache_policy_details"
)

Expand Down
Loading

0 comments on commit 57d2134

Please sign in to comment.