Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGES.txt
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ Other
-----

* Changed filter for tidy from ``tidy5`` to ``tidy``.
* Converted from .format() to f-strings

New in v8.3.1
=============
Expand Down
2 changes: 1 addition & 1 deletion dodo.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,5 +53,5 @@ def task_gen_completion():
yield {
'name': shell,
'actions': [cmd.format(shell)],
'targets': ['_nikola_{0}'.format(shell)],
'targets': [f'_nikola_{shell}'],
}
24 changes: 12 additions & 12 deletions nikola/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,15 +139,15 @@ def main(args=None):
except Exception:
if os.path.exists(conf_filename):
msg = traceback.format_exc()
LOGGER.error('"{0}" cannot be parsed.\n{1}'.format(conf_filename, msg))
LOGGER.error(f'"{conf_filename}" cannot be parsed.\n{msg}')
return 1
elif needs_config_file and conf_filename_changed:
LOGGER.error('Cannot find configuration file "{0}".'.format(conf_filename))
LOGGER.error(f'Cannot find configuration file "{conf_filename}".')
return 1
config = {}

if conf_filename_changed:
LOGGER.info("Using config file '{0}'".format(conf_filename))
LOGGER.info(f"Using config file '{conf_filename}'")

if config:
if os.path.isdir('plugins') and not os.path.exists('plugins/__init__.py'):
Expand Down Expand Up @@ -186,7 +186,7 @@ def print_usage(cmds):
print("Available commands:")
for cmd_name in sorted(cmds.keys()):
cmd = cmds[cmd_name]
print(" nikola {:20s} {}".format(cmd_name, cmd.doc_purpose))
print(f" nikola {cmd_name:20s} {cmd.doc_purpose}")
print("")
print(" nikola help show help / reference")
print(" nikola help <command> show command usage")
Expand Down Expand Up @@ -359,7 +359,7 @@ def run(self, cmd_args):
cmd_args = ['version']
args = ['version']
if args[0] not in sub_cmds.keys():
LOGGER.error("Unknown command {0}".format(args[0]))
LOGGER.error(f"Unknown command {args[0]}")
sugg = defaultdict(list)
sub_filtered = (i for i in sub_cmds.keys() if i != 'run')
for c in sub_filtered:
Expand All @@ -368,7 +368,7 @@ def run(self, cmd_args):
if sugg.keys():
best_sugg = sugg[min(sugg.keys())]
if len(best_sugg) == 1:
LOGGER.info('Did you mean "{}"?'.format(best_sugg[0]))
LOGGER.info(f'Did you mean "{best_sugg[0]}"?')
else:
LOGGER.info('Did you mean "{}" or "{}"?'.format('", "'.join(best_sugg[:-1]), best_sugg[-1]))
return 3
Expand Down Expand Up @@ -400,7 +400,7 @@ def _command_help(self: Command):
"""Return help text for a command."""
text = []

usage = "{} {} {}".format(self.bin_name, self.name, self.doc_usage)
usage = f"{self.bin_name} {self.name} {self.doc_usage}"
text.extend(textwrap.wrap(usage, subsequent_indent=' '))
text.extend(_wrap(self.doc_purpose, 4))

Expand All @@ -410,7 +410,7 @@ def _command_help(self: Command):
options[opt.section].append(opt)
for section, opts in sorted(options.items()):
if section:
section_name = '\n{}'.format(section)
section_name = f'\n{section}'
text.extend(_wrap(section_name, 2))
for opt in opts:
# ignore option that cant be modified on cmd line
Expand All @@ -421,15 +421,15 @@ def _command_help(self: Command):
if '%(default)s' in opt_help:
opt_help = opt.help % {'default': opt.default}
elif opt.default != '' and opt.default is not False and opt.default is not None:
opt_help += ' [default: {}]'.format(opt.default)
opt_help += f' [default: {opt.default}]'
opt_choices = opt.help_choices()
desc = '{} {}'.format(opt_help, opt_choices)
desc = f'{opt_help} {opt_choices}'
text.extend(_wrap(desc, 8))

# print bool inverse option
if opt.inverse:
text.extend(_wrap('--{}'.format(opt.inverse), 4))
text.extend(_wrap('opposite of --{}'.format(opt.long), 8))
text.extend(_wrap(f'--{opt.inverse}', 4))
text.extend(_wrap(f'opposite of --{opt.long}', 8))

if self.doc_description is not None:
text.append("\n\nDescription:")
Expand Down
21 changes: 8 additions & 13 deletions nikola/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,36 +168,33 @@ def yui_compressor(infile, executable=None):
raise Exception('yui-compressor is not installed.')
return False

return runinplace('{} --nomunge %1 -o %2'.format(yuicompressor), infile)
return runinplace(f'{yuicompressor} --nomunge %1 -o %2', infile)


@_ConfigurableFilter(executable='CLOSURE_COMPILER_EXECUTABLE')
def closure_compiler(infile, executable='closure-compiler'):
"""Run closure-compiler on a file."""
return runinplace(
'{} --warning_level QUIET --js %1 --js_output_file %2'.format(executable),
infile,
f'{executable} --warning_level QUIET --js %1 --js_output_file %2', infile
)


@_ConfigurableFilter(executable='OPTIPNG_EXECUTABLE')
def optipng(infile, executable='optipng'):
"""Run optipng on a file."""
return runinplace('{} -preserve -o2 -quiet %1'.format(executable), infile)
return runinplace(f'{executable} -preserve -o2 -quiet %1', infile)


@_ConfigurableFilter(executable='JPEGOPTIM_EXECUTABLE')
def jpegoptim(infile, executable='jpegoptim'):
"""Run jpegoptim on a file."""
return runinplace('{} -p --strip-all -q %1'.format(executable), infile)
return runinplace(f'{executable} -p --strip-all -q %1', infile)


@_ConfigurableFilter(executable='JPEGOPTIM_EXECUTABLE')
def jpegoptim_progressive(infile, executable='jpegoptim'):
"""Run jpegoptim on a file and convert to progressive."""
return runinplace(
'{} -p --strip-all --all-progressive -q %1'.format(executable), infile
)
return runinplace(f'{executable} -p --strip-all --all-progressive -q %1', infile)


@_ConfigurableFilter(executable='HTML_TIDY_EXECUTABLE')
Expand Down Expand Up @@ -532,9 +529,7 @@ def add_header_permalinks(fname, xpath_list=None, file_blacklist=None):
hid = node.attrib['id']

new_node = lxml.html.fragment_fromstring(
'<a href="#{0}" class="headerlink" title="Permalink to this heading">¶</a>'.format(
hid
)
f'<a href="#{hid}" class="headerlink" title="Permalink to this heading">¶</a>'
)
node.append(new_node)

Expand Down Expand Up @@ -563,7 +558,7 @@ def deduplicate_ids(data, top_classes=None):
# Well, that sucks.
for i in duplicated_ids:
# Results are ordered the same way they are ordered in document
offending_elements = doc.xpath('//*[@id="{}"]'.format(i))
offending_elements = doc.xpath(f'//*[@id="{i}"]')
counter = 2
# If this is a story or a post, do it from top to bottom, because
# updates to those are more likely to appear at the bottom of pages.
Expand All @@ -578,7 +573,7 @@ def deduplicate_ids(data, top_classes=None):
for e in off:
new_id = i
while new_id in seen_ids:
new_id = '{0}-{1}'.format(i, counter)
new_id = f'{i}-{counter}'
counter += 1
e.attrib['id'] = new_id
seen_ids.add(new_id)
Expand Down
8 changes: 4 additions & 4 deletions nikola/hierarchy_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,13 +96,13 @@ def __str__(self):
def _repr_partial(self):
"""Return partial representation."""
if self.parent:
return "{0}/{1!r}".format(self.parent._repr_partial(), self.name)
return f"{self.parent._repr_partial()}/{self.name!r}"
else:
return repr(self.name)

def __repr__(self):
"""Return programmer-friendly node representation."""
return "<TreeNode {0}>".format(self._repr_partial())
return f"<TreeNode {self._repr_partial()}>"


def clone_treenode(treenode, parent=None, acceptor=lambda x: True):
Expand Down Expand Up @@ -188,10 +188,10 @@ def parse_escaped_hierarchical_category_name(category_name):
next_slash = category_name.find('/', index)
else:
if len(category_name) == next_backslash + 1:
raise Exception("Unexpected '\\' in '{0}' at last position!".format(category_name))
raise Exception(f"Unexpected '\\' in '{category_name}' at last position!")
esc_ch = category_name[next_backslash + 1]
if esc_ch not in {'/', '\\'}:
raise Exception("Unknown escape sequence '\\{0}' in '{1}'!".format(esc_ch, category_name))
raise Exception(f"Unknown escape sequence '\\{esc_ch}' in '{category_name}'!")
current = (current if current else "") + category_name[index:next_backslash] + esc_ch
index = next_backslash + 2
next_backslash = category_name.find('\\', index)
Expand Down
10 changes: 5 additions & 5 deletions nikola/image_processing.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ def resize_image(self, src, dst=None, max_size=None, bigger_panoramas=True, pres
if max_sizes is None:
max_sizes = [max_size]
if len(max_sizes) != len(dst_paths):
raise ValueError('resize_image called with incompatible arguments: {} / {}'.format(dst_paths, max_sizes))
raise ValueError(f'resize_image called with incompatible arguments: {dst_paths} / {max_sizes}')
extension = os.path.splitext(src)[1].lower()
if extension in {'.svg', '.svgz'}:
self.resize_svg(src, dst_paths, max_sizes, bigger_panoramas)
Expand Down Expand Up @@ -169,8 +169,8 @@ def resize_image(self, src, dst=None, max_size=None, bigger_panoramas=True, pres

im.save(dst, **save_args)
except Exception as e:
self.logger.warning("Can't process {0}, using original "
"image! ({1})".format(src, e))
self.logger.warning(f"Can't process {src}, using original "
f"image! ({e})")
utils.copy_file(src, dst)

def resize_svg(self, src, dst_paths, max_sizes, bigger_panoramas):
Expand Down Expand Up @@ -217,8 +217,8 @@ def resize_svg(self, src, dst_paths, max_sizes, bigger_panoramas):
self.logger.warning("No width/height in %s. Original exception: %s" % (src, e))
utils.copy_file(src, dst)
except Exception as e:
self.logger.warning("Can't process {0}, using original "
"image! ({1})".format(src, e))
self.logger.warning(f"Can't process {src}, using original "
f"image! ({e})")
utils.copy_file(src, dst)

def image_date(self, src):
Expand Down
2 changes: 1 addition & 1 deletion nikola/log.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ def showwarning(message, category, filename, lineno, file=None, line=None):
n = category.__name__
except AttributeError:
n = str(category)
get_logger(n).warning("{0}:{1}: {2}".format(filename, lineno, message))
get_logger(n).warning(f"{filename}:{lineno}: {message}")


warnings.showwarning = showwarning
Loading