Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sourcery refactored develop branch #1

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
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
40 changes: 19 additions & 21 deletions src/sphinxcontrib/bibtex/domain.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ def _raise_invalid_node(node):
"""Helper method to raise an exception when an invalid node is
visited.
"""
raise ValueError("invalid node %s in filter expression" % node)
raise ValueError(f"invalid node {node} in filter expression")
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _raise_invalid_node refactored with the following changes:



class _FilterVisitor(ast.NodeVisitor):
Expand Down Expand Up @@ -95,7 +95,7 @@ def visit_BoolOp(self, node):
else: # pragma: no cover
# there are no other boolean operators
# so this code should never execute
assert False, "unexpected boolean operator %s" % node.op
assert False, f"unexpected boolean operator {node.op}"
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _FilterVisitor.visit_BoolOp refactored with the following changes:


def visit_UnaryOp(self, node):
if isinstance(node.op, ast.Not):
Expand All @@ -110,11 +110,9 @@ def visit_BinOp(self, node):
if isinstance(op, ast.Mod):
# modulo operator is used for regular expression matching
if not isinstance(left, str):
raise ValueError(
"expected a string on left side of %s" % node.op)
raise ValueError(f"expected a string on left side of {node.op}")
if not isinstance(right, str):
raise ValueError(
"expected a string on right side of %s" % node.op)
raise ValueError(f"expected a string on right side of {node.op}")
Comment on lines -113 to +115
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _FilterVisitor.visit_BinOp refactored with the following changes:

return re.search(right, left, re.IGNORECASE)
elif isinstance(op, ast.BitOr):
return left | right
Expand Down Expand Up @@ -163,7 +161,7 @@ def visit_Name(self, node):
return self.docname
elif id_ == 'docnames':
return self.cited_docnames
elif id_ == 'author' or id_ == 'editor':
elif id_ in ['author', 'editor']:
Comment on lines -166 to +164
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _FilterVisitor.visit_Name refactored with the following changes:

if id_ in self.entry.persons:
return u' and '.join(
str(person) # XXX needs fix in pybtex?
Expand Down Expand Up @@ -203,8 +201,7 @@ def get_docnames(env):
yield docname
parent, prevdoc, nextdoc = rel[docname]
docname = nextdoc
for docname in sorted(env.found_docs - docnames):
yield docname
yield from sorted(env.found_docs - docnames)
Comment on lines -206 to +204
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function get_docnames refactored with the following changes:

  • Replace yield inside for loop with yield from (yield-from)



class Citation(NamedTuple):
Expand Down Expand Up @@ -287,7 +284,7 @@ def __init__(self, env: "BuildEnvironment"):
self.object_types = dict(
citation=ObjType(_('citation'), *role_names, searchprio=-1),
)
self.roles = dict((name, CiteRole()) for name in role_names)
self.roles = {name: CiteRole() for name in role_names}
Comment on lines -290 to +287
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function BibtexDomain.__init__ refactored with the following changes:

This removes the following comments ( why? ):

# parse bibliography header

# initialize the domain
super().__init__(env)
# connect env-updated
Expand All @@ -298,13 +295,13 @@ def __init__(self, env: "BuildEnvironment"):
"You must configure the bibtex_bibfiles setting")
# update bib file information in the cache
bibfiles = [
normpath_filename(env, "/" + bibfile)
for bibfile in env.app.config.bibtex_bibfiles]
normpath_filename(env, f"/{bibfile}")
for bibfile in env.app.config.bibtex_bibfiles
]

self.data['bibdata'] = process_bibdata(
self.bibdata, bibfiles, env.app.config.bibtex_encoding)
# parse bibliography header
header = getattr(env.app.config, "bibtex_bibliography_header")
if header:
if header := getattr(env.app.config, "bibtex_bibliography_header"):
self.data["bibliography_header"] += \
parse_header(header, "bibliography_header")

Expand Down Expand Up @@ -434,8 +431,7 @@ def get_all_cited_keys(self, docnames):
"""
for citation_ref in sorted(
self.citation_refs, key=lambda c: docnames.index(c.docname)):
for key in citation_ref.keys:
yield key
yield from citation_ref.keys
Comment on lines -437 to +434
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function BibtexDomain.get_all_cited_keys refactored with the following changes:

  • Replace yield inside for loop with yield from (yield-from)


def get_entries(
self, bibfiles: List[str]) -> Iterable["Entry"]:
Expand Down Expand Up @@ -468,9 +464,12 @@ def get_filtered_entries(
success = visitor.visit(bibliography.filter_)
except ValueError as err:
logger.warning(
"syntax error in :filter: expression; %s" % err,
f"syntax error in :filter: expression; {err}",
location=(bibliography_key.docname, bibliography.line),
type="bibtex", subtype="filter_syntax_error")
type="bibtex",
subtype="filter_syntax_error",
)

Comment on lines -471 to +472
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function BibtexDomain.get_filtered_entries refactored with the following changes:

# recover by falling back to the default
success = bool(cited_docnames)
if success or entry.key in bibliography.keys:
Expand All @@ -490,8 +489,7 @@ def get_sorted_entries(
else:
yield key, entry
# then all remaining keys, in order of bibliography file
for key, entry in entries.items():
yield key, entry
yield from entries.items()
Comment on lines -493 to +492
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function BibtexDomain.get_sorted_entries refactored with the following changes:

  • Replace yield inside for loop with yield from (yield-from)


def get_formatted_entries(
self, bibliography_key: "BibliographyKey", docnames: List[str],
Expand Down
37 changes: 18 additions & 19 deletions src/sphinxcontrib/bibtex/foot_directives.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,22 +35,21 @@ def run(self):
env.temp_data.get("bibtex_footbibliography_count", 0) + 1
if not foot_new_refs:
return []
else:
foot_old_refs |= foot_new_refs
foot_new_refs.clear()
# bibliography stored in env.temp_data["bibtex_foot_bibliography"]
foot_domain = cast("BibtexFootDomain", env.get_domain('footcite'))
foot_bibliography, env.temp_data["bibtex_foot_bibliography"] = (
env.temp_data["bibtex_foot_bibliography"],
foot_domain.bibliography_header.deepcopy())
domain = cast("BibtexDomain", env.get_domain('cite'))
for bibfile in domain.bibdata.bibfiles:
env.note_dependency(bibfile)
foot_bibliography['ids'] += _make_ids(
docname=env.docname, lineno=self.lineno,
ids=set(self.state.document.ids.keys()),
raw_id=env.app.config.bibtex_footbibliography_id.format(
footbibliography_count=footbibliography_count))
self.state.document.note_explicit_target(
foot_bibliography, foot_bibliography)
return [foot_bibliography]
foot_old_refs |= foot_new_refs
foot_new_refs.clear()
# bibliography stored in env.temp_data["bibtex_foot_bibliography"]
foot_domain = cast("BibtexFootDomain", env.get_domain('footcite'))
foot_bibliography, env.temp_data["bibtex_foot_bibliography"] = (
env.temp_data["bibtex_foot_bibliography"],
foot_domain.bibliography_header.deepcopy())
domain = cast("BibtexDomain", env.get_domain('cite'))
for bibfile in domain.bibdata.bibfiles:
env.note_dependency(bibfile)
foot_bibliography['ids'] += _make_ids(
docname=env.docname, lineno=self.lineno,
ids=set(self.state.document.ids.keys()),
raw_id=env.app.config.bibtex_footbibliography_id.format(
footbibliography_count=footbibliography_count))
self.state.document.note_explicit_target(
foot_bibliography, foot_bibliography)
return [foot_bibliography]
Comment on lines -38 to +55
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function FootBibliographyDirective.run refactored with the following changes:

6 changes: 2 additions & 4 deletions src/sphinxcontrib/bibtex/foot_domain.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,12 +54,10 @@ def __init__(self, env: "BuildEnvironment"):
self.object_types = dict(
citation=ObjType(_('citation'), *role_names, searchprio=-1),
)
self.roles = dict((name, FootCiteRole()) for name in role_names)
self.roles = {name: FootCiteRole() for name in role_names}
# initialize the domain
super().__init__(env)
# parse bibliography header
header = getattr(env.app.config, "bibtex_footbibliography_header")
if header:
if header := getattr(env.app.config, "bibtex_footbibliography_header"):
Comment on lines -57 to +60
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function BibtexFootDomain.__init__ refactored with the following changes:

This removes the following comments ( why? ):

# parse bibliography header

self.data["bibliography_header"] += \
parse_header(header, "foot_bibliography_header")

Expand Down
5 changes: 1 addition & 4 deletions src/sphinxcontrib/bibtex/foot_roles.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,10 +78,7 @@ def result_nodes(self, document: "docutils.nodes.document",
if key not in (foot_old_refs | foot_new_refs):
footnote = docutils.nodes.footnote(auto=1)
# no automatic ids for footnotes: force non-empty template
template: str = \
env.app.config.bibtex_footcite_id \
if env.app.config.bibtex_footcite_id \
else "footcite-{key}"
template: str = env.app.config.bibtex_footcite_id or "footcite-{key}"
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function FootCiteRole.result_nodes refactored with the following changes:

raw_id = template.format(
footbibliography_count=footbibliography_count + 1,
key=entry.key)
Expand Down
4 changes: 3 additions & 1 deletion src/sphinxcontrib/bibtex/style/template.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,9 @@ def render(self, backend: "BaseBackend"):
info = self.info[0]
# see docutils.parsers.rst.states.Body.footnote_reference()
refnode = docutils.nodes.footnote_reference(
'[#%s]_' % info.key, refname=info.refname, auto=1)
f'[#{info.key}]_', refname=info.refname, auto=1
)

Comment on lines -186 to +188
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function FootReferenceText.render refactored with the following changes:

info.document.note_autofootnote_ref(refnode)
info.document.note_footnote_ref(refnode)
return [refnode]
Expand Down
16 changes: 6 additions & 10 deletions src/sphinxcontrib/bibtex/transforms.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,23 +80,19 @@ def run(self, **kwargs):
nodes = []
for citation in citations:
citation_node = bibliography.citation_nodes[citation.key]
if bibliography.list_ in {"enumerated", "bullet"}:
citation_node += self.backend.paragraph(
citation.formatted_entry)
else: # "citation"
# backrefs only supported in same document
backrefs = [
if bibliography.list_ not in {"enumerated", "bullet"}:
if backrefs := [
citation_ref.citation_ref_id
for citation_ref in domain.citation_refs
if bib_key.docname == citation_ref.docname
and citation.key in citation_ref.keys]
if backrefs:
and citation.key in citation_ref.keys
]:
citation_node['backrefs'] = backrefs
citation_node += docutils.nodes.label(
'', citation.formatted_entry.label,
support_smartquotes=False)
citation_node += self.backend.paragraph(
citation.formatted_entry)
citation_node += self.backend.paragraph(
citation.formatted_entry)
Comment on lines -83 to +95
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function BibliographyTransform.run refactored with the following changes:

This removes the following comments ( why? ):

# backrefs only supported in same document
# "citation"

citation_node['docname'] = bib_key.docname
node_text_transform(citation_node)
nodes.append(citation_node)
Expand Down
Loading