Skip to content

Commit

Permalink
lint and fix using pyupgrade (#418)
Browse files Browse the repository at this point in the history
  • Loading branch information
danieleades authored Nov 30, 2021
1 parent fb8dc05 commit 62ba15e
Show file tree
Hide file tree
Showing 96 changed files with 112 additions and 183 deletions.
7 changes: 7 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,10 @@ repos:
rev: 5.9.3
hooks:
- id: isort

- repo: https://github.com/asottile/pyupgrade
rev: v2.29.1
hooks:
- id: pyupgrade
args:
- --py36-plus
8 changes: 4 additions & 4 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,9 +257,9 @@
if on_rtd:
# Deactivated using rtd plantuml version as it looks quite old.
# plantuml = 'java -Djava.awt.headless=true -jar /usr/share/plantuml/plantuml.jar'
plantuml = "java -Djava.awt.headless=true -jar {}".format(local_plantuml_path)
plantuml = f"java -Djava.awt.headless=true -jar {local_plantuml_path}"
else:
plantuml = "java -jar {}".format(local_plantuml_path)
plantuml = f"java -jar {local_plantuml_path}"

# plantuml_output_format = 'png'
plantuml_output_format = "svg_img"
Expand Down Expand Up @@ -343,7 +343,7 @@
github_token = os.environ.get("GITHUB_TOKEN", "")

if github_username != "" and github_token != "":
print("GITHUB: Using as username: {}. lenth token: {}".format(github_username, len(github_token)))
print(f"GITHUB: Using as username: {github_username}. lenth token: {len(github_token)}")
for service in ["github-issues", "github-prs", "github-commits"]:
needs_services[service]["username"] = github_username
needs_services[service]["token"] = github_token
Expand All @@ -365,7 +365,7 @@
# General information about the project.
project = "Sphinx-Needs"
now = datetime.datetime.now()
copyright = '2017-{year}, <a href="http://useblocks.com">team useblocks</a>'.format(year=now.year)
copyright = f'2017-{now.year}, <a href="http://useblocks.com">team useblocks</a>'
author = "team useblocks"

# The language for content autogenerated by Sphinx. Refer to documentation
Expand Down
2 changes: 1 addition & 1 deletion performance/performance_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,7 @@ def series(
]
print(tabulate(result_table, headers=headers))

overall_runtime = sum([x[1] for x in results])
overall_runtime = sum(x[1] for x in results)
print(f"\nOverall runtime: {overall_runtime:.2f} seconds.")

if snakeviz:
Expand Down
4 changes: 2 additions & 2 deletions sphinxcontrib/needs/api/configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ def add_need_type(app: Sphinx, directive, title, prefix, color="#ffffff", style=
type_names = [x["directive"] for x in needs_types]

if directive in type_names:
raise NeedsApiConfigException("{} already exists as need type".format(directive))
raise NeedsApiConfigException(f"{directive} already exists as need type")

needs_types.append({"directive": directive, "title": title, "prefix": prefix, "color": color, "style": style})
app.add_directive(directive, sphinxcontrib.needs.directives.need.NeedDirective)
Expand All @@ -85,7 +85,7 @@ def add_extra_option(app, name):
extra_options = NEEDS_CONFIG.create_or_get("extra_options", dict)

if name in extra_options:
raise NeedsApiConfigWarning("Option {} already registered.".format(name))
raise NeedsApiConfigWarning(f"Option {name} already registered.")

NEEDS_CONFIG.add("extra_options", {name: directives.unchanged}, dict, append=True)
# extra_options[name] = directives.unchanged
Expand Down
36 changes: 16 additions & 20 deletions sphinxcontrib/needs/api/need.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def add_need(
is_external=False,
external_url=None,
external_css="external_link",
**kwargs
**kwargs,
):
"""
Creates a new need and returns its node.
Expand Down Expand Up @@ -180,7 +180,7 @@ def run():
# Check if status is in needs_statuses. If not raise an error.
if env.app.config.needs_statuses and status not in [stat["name"] for stat in env.app.config.needs_statuses]:
raise NeedsStatusNotAllowed(
"Status {0} of need id {1} is not allowed " "by config value 'needs_statuses'.".format(status, need_id)
f"Status {status} of need id {need_id} is not allowed " "by config value 'needs_statuses'."
)

if tags is None:
Expand All @@ -193,9 +193,7 @@ def run():
new_tags = [] # Shall contain only valid tags
for i in range(len(tags)):
if len(tags[i]) == 0 or tags[i].isspace():
logger.warning(
"Scruffy tag definition found in need {}. " "Defined tag contains spaces only.".format(need_id)
)
logger.warning(f"Scruffy tag definition found in need {need_id}. " "Defined tag contains spaces only.")
else:
new_tags.append(tags[i])

Expand All @@ -205,7 +203,7 @@ def run():
for tag in tags:
if tag not in [tag["name"] for tag in env.app.config.needs_tags]:
raise NeedsTagNotAllowed(
"Tag {0} of need id {1} is not allowed " "by config value 'needs_tags'.".format(tag, need_id)
f"Tag {tag} of need id {need_id} is not allowed " "by config value 'needs_tags'."
)
# This may have cut also dynamic function strings, as they can contain , as well.
# So let put them together again
Expand All @@ -222,8 +220,8 @@ def run():
if need_id in env.needs_all_needs:
if id:
raise NeedsDuplicatedId(
"A need with ID {} already exists! "
"This is not allowed. Document {}[{}] Title: {}.".format(need_id, docname, lineno, title)
f"A need with ID {need_id} already exists! "
f"This is not allowed. Document {docname}[{lineno}] Title: {title}."
)
else: # this is a generated ID
raise NeedsDuplicatedId(
Expand Down Expand Up @@ -361,7 +359,7 @@ def run():
# Title and meta data information gets added alter during event handling via process_need_nodes()
# We just add a basic need node and render the rst-based content, because this can not be done later.
# style_classes = ['need', type_name, 'need-{}'.format(type_name.lower())] # Used < 0.4.4
style_classes = ["need", "need-{}".format(need_type.lower())]
style_classes = ["need", f"need-{need_type.lower()}"]
if style:
style_classes.append(style)

Expand Down Expand Up @@ -403,7 +401,7 @@ def del_need(app, id):
if id in app.env.needs_all_needs:
del app.env.needs_all_needs[id]
else:
logger.warning("Given need id {} not exists!".format(id))
logger.warning(f"Given need id {id} not exists!")


def add_external_need(
Expand All @@ -417,7 +415,7 @@ def add_external_need(
status=None,
tags=None,
links_string=None,
**kwargs
**kwargs,
):
"""
Adds an external need from an external source.
Expand Down Expand Up @@ -465,14 +463,14 @@ def _prepare_template(app, needs_info, template_key):
template_folder = os.path.join(app.confdir, template_folder)

if not os.path.isdir(template_folder):
raise NeedsTemplateException("Template folder does not exist: {}".format(template_folder))
raise NeedsTemplateException(f"Template folder does not exist: {template_folder}")

template_file_name = needs_info[template_key] + ".need"
template_path = os.path.join(template_folder, template_file_name)
if not os.path.isfile(template_path):
raise NeedsTemplateException("Template does not exist: {}".format(template_path))
raise NeedsTemplateException(f"Template does not exist: {template_path}")

with open(template_path, "r") as template_file:
with open(template_path) as template_file:
template_content = "".join(template_file.readlines())
template_obj = Template(template_content)
new_content = template_obj.render(**needs_info)
Expand Down Expand Up @@ -502,9 +500,7 @@ def _read_in_links(links_string: Union[str, List[str]]):
link_list = links_string
for link in link_list:
if link.isspace():
logger.warning(
"Grubby link definition found in need {}. " "Defined link contains spaces only.".format(id)
)
logger.warning(f"Grubby link definition found in need {id}. " "Defined link contains spaces only.")
else:
links.append(link.strip())

Expand Down Expand Up @@ -536,10 +532,10 @@ def make_hashed_id(app, need_type, full_title, content, id_length=None):
type_prefix = ntype["prefix"]
break
if type_prefix is None:
raise NeedsInvalidException("Given need_type {} is unknown. File {}".format(need_type, app.env.docname))
raise NeedsInvalidException(f"Given need_type {need_type} is unknown. File {app.env.docname}")

hashable_content = full_title or "\n".join(content)
return "%s%s" % (type_prefix, hashlib.sha1(hashable_content.encode("UTF-8")).hexdigest().upper()[:id_length])
return "{}{}".format(type_prefix, hashlib.sha1(hashable_content.encode("UTF-8")).hexdigest().upper()[:id_length])


def _fix_list_dyn_func(list):
Expand Down Expand Up @@ -621,7 +617,7 @@ def _merge_global_options(app, needs_info, global_options):

for single_value in values:
if len(single_value) < 2 or len(single_value) > 3:
raise NeedsInvalidException("global option tuple has wrong amount of parameters: {}".format(key))
raise NeedsInvalidException(f"global option tuple has wrong amount of parameters: {key}")
if filter_single_need(app, needs_info, single_value[1]):
# Set value, if filter has matched
needs_info[key] = single_value[0]
Expand Down
2 changes: 1 addition & 1 deletion sphinxcontrib/needs/builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def finish(self):
try:
needs_list.write_json()
except Exception as e:
log.error("Error during writing json file: {0}".format(e))
log.error(f"Error during writing json file: {e}")
else:
log.info("Needs successfully exported")

Expand Down
8 changes: 4 additions & 4 deletions sphinxcontrib/needs/diagrams_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def prepare_env(self, env_var):
def create_target(self, target_name):
env = self.state.document.settings.env
id = env.new_serialno(target_name)
targetid = "{targetname}-{docname}-{id}".format(targetname=target_name, docname=env.docname, id=id)
targetid = f"{target_name}-{env.docname}-{id}"
targetnode = nodes.target("", "", ids=[targetid])

return id, targetid, targetnode
Expand Down Expand Up @@ -78,9 +78,9 @@ def collect_diagram_attributes(self):

scale = self.options.get("scale", "100").replace("%", "")
if not scale.isdigit():
raise Exception('Needsequence scale value must be a number. "{}" found'.format(scale))
raise Exception(f'Needsequence scale value must be a number. "{scale}" found')
if int(scale) < 1 or int(scale) > 300:
raise Exception('Needsequence scale value must be between 1 and 300. "{}" found'.format(scale))
raise Exception(f'Needsequence scale value must be between 1 and 300. "{scale}" found')

highlight = self.options.get("highlight", "")

Expand Down Expand Up @@ -159,7 +159,7 @@ def get_debug_container(puml_node):
else:
data = puml_node["uml"]
data = "\n".join([html.escape(line) for line in data.split("\n")])
debug_para = nodes.raw("", "<pre>{}</pre>".format(data), format="html")
debug_para = nodes.raw("", f"<pre>{data}</pre>", format="html")
debug_container += debug_para

return debug_container
Expand Down
11 changes: 6 additions & 5 deletions sphinxcontrib/needs/directives/need.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
import hashlib
import re

Expand Down Expand Up @@ -130,7 +129,9 @@ def read_in_links(self, name):

def make_hashed_id(self, type_prefix, id_length):
hashable_content = self.full_title or "\n".join(self.content)
return "%s%s" % (type_prefix, hashlib.sha1(hashable_content.encode("UTF-8")).hexdigest().upper()[:id_length])
return "{}{}".format(
type_prefix, hashlib.sha1(hashable_content.encode("UTF-8")).hexdigest().upper()[:id_length]
)

@property
def env(self):
Expand Down Expand Up @@ -345,8 +346,8 @@ def create_back_links(env, option):
:param env: sphinx enviroment
:return: None
"""
option_back = "{}_back".format(option)
if env.needs_workflow["backlink_creation_{}".format(option)]:
option_back = f"{option}_back"
if env.needs_workflow[f"backlink_creation_{option}"]:
return

needs = env.needs_all_needs
Expand All @@ -368,7 +369,7 @@ def create_back_links(env, option):
needs[link_main]["parts"][link_part][option_back] = []
needs[link_main]["parts"][link_part][option_back].append(key)

env.needs_workflow["backlink_creation_{}".format(option)] = True
env.needs_workflow[f"backlink_creation_{option}"] = True


def _fix_list_dyn_func(list):
Expand Down
2 changes: 1 addition & 1 deletion sphinxcontrib/needs/directives/needextend.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def run(self):
env.needs_all_needs = {}

id = env.new_serialno("needextend")
targetid = "needextend-{docname}-{id}".format(docname=env.docname, id=id)
targetid = f"needextend-{env.docname}-{id}"
targetnode = nodes.target("", "", ids=[targetid])

extend_filter = self.arguments[0] if self.arguments else None
Expand Down
4 changes: 2 additions & 2 deletions sphinxcontrib/needs/directives/needfilter.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ def process_needfilters(app, doctree, fromdocname):
for need_info in found_needs:
if current_needfilter["layout"] == "list":
para = nodes.line()
description = "%s: %s" % (need_info["id"], need_info["title"])
description = "{}: {}".format(need_info["id"], need_info["title"])

if current_needfilter["show_status"] and need_info["status"]:
description += " (%s)" % need_info["status"]
Expand Down Expand Up @@ -192,7 +192,7 @@ def process_needfilters(app, doctree, fromdocname):
link = (
"../"
+ app.builder.get_target_uri(need_info["docname"])
+ "?highlight={0}".format(urlparse(need_info["title"]))
+ "?highlight={}".format(urlparse(need_info["title"]))
+ "#"
+ need_info["target_node"]["refid"]
) # Gets mostly called during latex generation
Expand Down
12 changes: 6 additions & 6 deletions sphinxcontrib/needs/directives/needflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def run(self):
env.needs_all_needs = {}

id = env.new_serialno("needflow")
targetid = "needflow-{docname}-{id}".format(docname=env.docname, id=id)
targetid = f"needflow-{env.docname}-{id}"
targetnode = nodes.target("", "", ids=[targetid])

all_link_types = ",".join(x["option"] for x in env.config.needs_extra_links)
Expand All @@ -73,9 +73,9 @@ def run(self):

scale = self.options.get("scale", "100").replace("%", "")
if not scale.isdigit():
raise Exception('Needflow scale value must be a number. "{}" found'.format(scale))
raise Exception(f'Needflow scale value must be a number. "{scale}" found')
if int(scale) < 1 or int(scale) > 300:
raise Exception('Needflow scale value must be between 1 and 300. "{}" found'.format(scale))
raise Exception(f'Needflow scale value must be between 1 and 300. "{scale}" found')

highlight = self.options.get("highlight", "")

Expand Down Expand Up @@ -249,7 +249,7 @@ def process_needflow(app, doctree, fromdocname):
# Only add subelements and their {...} container, if we really need them.
# Otherwise plantuml may not set style correctly, if {..} is empty
if node_part_code:
node_part_code = "{{\n {} }}".format(node_part_code)
node_part_code = f"{{\n {node_part_code} }}"

style = need_info["type_style"]

Expand Down Expand Up @@ -277,7 +277,7 @@ def process_needflow(app, doctree, fromdocname):
final_link = link
if current_needflow["show_link_names"] or env.config.needs_flow_show_links:
desc = link_type["outgoing"] + "\\n"
comment = ": {desc}".format(desc=desc)
comment = f": {desc}"
else:
comment = ""

Expand Down Expand Up @@ -399,7 +399,7 @@ def process_needflow(app, doctree, fromdocname):
else:
data = puml_node["uml"]
data = "\n".join([html.escape(line) for line in data.split("\n")])
debug_para = nodes.raw("", "<pre>{}</pre>".format(data), format="html")
debug_para = nodes.raw("", f"<pre>{data}</pre>", format="html")
debug_container += debug_para
content += debug_container

Expand Down
4 changes: 2 additions & 2 deletions sphinxcontrib/needs/directives/needgantt.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,9 +180,9 @@ def process_needgantt(app, doctree, fromdocname):
)

month = MONTH_NAMES[int(start_date.strftime("%-m"))]
start_date_plantuml = start_date.strftime("%dth of {} %Y".format(month))
start_date_plantuml = start_date.strftime(f"%dth of {month} %Y")
if start_date_plantuml:
puml_node["uml"] += "Project starts the {}\n".format(start_date_plantuml)
puml_node["uml"] += f"Project starts the {start_date_plantuml}\n"

# Element handling
puml_node["uml"] += "\n' Elements definition \n\n"
Expand Down
15 changes: 5 additions & 10 deletions sphinxcontrib/needs/directives/needimport.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import os
import re

import six
from docutils import nodes
from docutils.parsers.rst import Directive, directives

Expand Down Expand Up @@ -73,9 +72,9 @@ def run(self):
correct_need_import_path = os.path.join(env.app.confdir, need_import_path[1:])

if not os.path.exists(correct_need_import_path):
raise ReferenceError("Could not load needs import file {0}".format(correct_need_import_path))
raise ReferenceError(f"Could not load needs import file {correct_need_import_path}")

with open(correct_need_import_path, "r") as needs_file:
with open(correct_need_import_path) as needs_file:
needs_file_content = needs_file.read()
try:
needs_import_list = json.loads(needs_file_content)
Expand All @@ -86,16 +85,12 @@ def run(self):
if version is None:
try:
version = needs_import_list["current_version"]
if not isinstance(version, six.string_types):
if not isinstance(version, str):
raise KeyError
except KeyError:
raise CorruptedNeedsFile(
"Key 'current_version' missing or corrupted in {0}".format(correct_need_import_path)
)
raise CorruptedNeedsFile(f"Key 'current_version' missing or corrupted in {correct_need_import_path}")
if version not in needs_import_list["versions"].keys():
raise VersionNotFound(
"Version {0} not found in needs import file {1}".format(version, correct_need_import_path)
)
raise VersionNotFound(f"Version {version} not found in needs import file {correct_need_import_path}")

needs_list = needs_import_list["versions"][version]["needs"]

Expand Down
Loading

0 comments on commit 62ba15e

Please sign in to comment.