Skip to content

Commit ed8e5c9

Browse files
committed
Reformat code for improved readability
Consolidated multi-line statements into single lines across multiple files to enhance code readability and maintain consistency. No functional changes were made.
1 parent d625661 commit ed8e5c9

12 files changed

Lines changed: 71 additions & 197 deletions

File tree

sphinx_external_toc/_compat.py

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,7 @@ def field(**kwargs: Any):
1919
if sys.version_info < (3, 10):
2020
kwargs.pop("kw_only", None)
2121
if "validator" in kwargs:
22-
kwargs.setdefault("metadata", {})["validator"] = kwargs.pop(
23-
"validator"
24-
)
22+
kwargs.setdefault("metadata", {})["validator"] = kwargs.pop("validator")
2523
return dc.field(**kwargs)
2624

2725

@@ -95,9 +93,7 @@ def matches_re(regex: str | Pattern, flags: int = 0) -> ValidatorType:
9593
if fullmatch:
9694
match_func = pattern.fullmatch
9795
else: # Python 2 fullmatch emulation (https://bugs.python.org/issue16203)
98-
pattern = re.compile(
99-
r"(?:{})\Z".format(pattern.pattern), pattern.flags
100-
)
96+
pattern = re.compile(r"(?:{})\Z".format(pattern.pattern), pattern.flags)
10197
match_func = pattern.match
10298

10399
def _validator(inst, attr, value):
@@ -170,6 +166,4 @@ def validate_style(instance, attribute, value):
170166
f"{attribute.name} must be one of {allowed}, not {v!r}"
171167
)
172168
elif value not in allowed:
173-
raise ValueError(
174-
f"{attribute.name} must be one of {allowed}, not {value!r}"
175-
)
169+
raise ValueError(f"{attribute.name} must be one of {allowed}, not {value!r}")

sphinx_external_toc/api.py

Lines changed: 6 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -37,9 +37,7 @@ class UrlItem:
3737

3838
# regex should match sphinx.util.url_re
3939
url: str = field(validator=[instance_of(str), matches_re(URL_PATTERN)])
40-
title: Optional[str] = field(
41-
default=None, validator=optional(instance_of(str))
42-
)
40+
title: Optional[str] = field(default=None, validator=optional(instance_of(str)))
4341

4442
def __post_init__(self):
4543
validate_fields(self)
@@ -58,19 +56,13 @@ class TocTree:
5856
caption: Optional[str] = field(
5957
default=None, kw_only=True, validator=optional(instance_of(str))
6058
)
61-
hidden: bool = field(
62-
default=True, kw_only=True, validator=instance_of(bool)
63-
)
59+
hidden: bool = field(default=True, kw_only=True, validator=instance_of(bool))
6460
maxdepth: int = field(default=-1, kw_only=True, validator=instance_of(int))
6561
numbered: Union[bool, int] = field(
6662
default=False, kw_only=True, validator=instance_of((bool, int))
6763
)
68-
reversed: bool = field(
69-
default=False, kw_only=True, validator=instance_of(bool)
70-
)
71-
titlesonly: bool = field(
72-
default=False, kw_only=True, validator=instance_of(bool)
73-
)
64+
reversed: bool = field(default=False, kw_only=True, validator=instance_of(bool))
65+
titlesonly: bool = field(default=False, kw_only=True, validator=instance_of(bool))
7466
# Add extra field for style of toctree rendering
7567
style: Union[List[str], str] = field(
7668
default="numerical", kw_only=True, validator=validate_style
@@ -109,9 +101,7 @@ class Document:
109101
default_factory=list,
110102
validator=deep_iterable(instance_of(TocTree), instance_of(list)),
111103
)
112-
title: Optional[str] = field(
113-
default=None, validator=optional(instance_of(str))
114-
)
104+
title: Optional[str] = field(default=None, validator=optional(instance_of(str)))
115105

116106
def __post_init__(self):
117107
validate_fields(self)
@@ -177,9 +167,7 @@ def file_format(self, value: Optional[str]) -> None:
177167

178168
def globs(self) -> Set[str]:
179169
"""Return set of all globs present across all toctrees."""
180-
return {
181-
glob for item in self._docs.values() for glob in item.child_globs()
182-
}
170+
return {glob for item in self._docs.values() for glob in item.child_globs()}
183171

184172
def __getitem__(self, docname: str) -> Document:
185173
"""Enable retrieving a document by name using the indexing operator.

sphinx_external_toc/cli.py

Lines changed: 6 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -27,11 +27,7 @@ def main():
2727
def parse_toc(toc_file):
2828
"""Parse a ToC file to a site-map YAML."""
2929
site_map = parse_toc_yaml(toc_file)
30-
click.echo(
31-
yaml.dump(
32-
site_map.as_json(), sort_keys=False, default_flow_style=False
33-
)
34-
)
30+
click.echo(yaml.dump(site_map.as_json(), sort_keys=False, default_flow_style=False))
3531

3632

3733
@main.command("to-project")
@@ -51,9 +47,7 @@ def parse_toc(toc_file):
5147
show_default=True,
5248
help="The default file extension to use.",
5349
)
54-
@click.option(
55-
"-o", "--overwrite", is_flag=True, help="Overwrite existing files."
56-
)
50+
@click.option("-o", "--overwrite", is_flag=True, help="Overwrite existing files.")
5751
def create_site(toc_file, path, extension, overwrite):
5852
"""Create a project directory from a ToC file."""
5953
create_site_from_toc(
@@ -107,9 +101,7 @@ def create_site(toc_file, path, extension, overwrite):
107101
show_default=True,
108102
help="The key-mappings to use.",
109103
)
110-
def create_toc(
111-
site_dir, extension, index, skip_match, guess_titles, file_format
112-
):
104+
def create_toc(site_dir, extension, index, skip_match, guess_titles, file_format):
113105
"""Create a ToC file from a project directory."""
114106
site_map = create_site_map_from_path(
115107
site_dir,
@@ -125,19 +117,11 @@ def create_toc(
125117
continue
126118
filepath = PurePosixPath(docname)
127119
# use the folder name for index files
128-
name = (
129-
filepath.parent.name
130-
if filepath.name == index
131-
else filepath.name
132-
)
120+
name = filepath.parent.name if filepath.name == index else filepath.name
133121
# split into words
134122
words = name.split("_")
135123
# remove first word if is an integer
136-
words = (
137-
words[1:]
138-
if words and all(c.isdigit() for c in words[0])
139-
else words
140-
)
124+
words = words[1:] if words and all(c.isdigit() for c in words[0]) else words
141125
site_map[docname].title = " ".join(words).capitalize()
142126
data = create_toc_dict(site_map)
143127
click.echo(yaml.dump(data, sort_keys=False, default_flow_style=False))
@@ -154,9 +138,7 @@ def create_toc(
154138
@click.option(
155139
"-o",
156140
"--output",
157-
type=click.Path(
158-
allow_dash=True, exists=False, file_okay=True, dir_okay=False
159-
),
141+
type=click.Path(allow_dash=True, exists=False, file_okay=True, dir_okay=False),
160142
help="Write to a file path.",
161143
)
162144
def migrate_toc(toc_file, format, output):

sphinx_external_toc/collectors.py

Lines changed: 8 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,7 @@ def __init__(self, *args, **kwargs):
3232

3333
def assign_section_numbers(self, env):
3434
# First, call the original assign_section_numbers to get the default behavior
35-
result = super().assign_section_numbers(
36-
env
37-
) # needed to maintain functionality
35+
result = super().assign_section_numbers(env) # needed to maintain functionality
3836

3937
# store current titles for mapping
4038
env.titles_old = copy.deepcopy(env.titles)
@@ -82,9 +80,7 @@ def assign_section_numbers(self, env):
8280
new_secnumber = self.__renumber(
8381
env.titles[ref]["secnumber"], style
8482
)
85-
env.titles[ref]["secnumber"] = copy.deepcopy(
86-
new_secnumber
87-
)
83+
env.titles[ref]["secnumber"] = copy.deepcopy(new_secnumber)
8884
if ref in env.tocs:
8985
self.__replace_toc(env, ref, env.tocs[ref], style)
9086

@@ -116,17 +112,13 @@ def assign_section_numbers(self, env):
116112
secnumber[i] == old_secnumber[i]
117113
): # only if the old matches the current
118114
update_secnumber[i] = new_secnumber[i]
119-
env.toc_secnumbers[doc][anchor] = copy.deepcopy(
120-
update_secnumber
121-
)
115+
env.toc_secnumbers[doc][anchor] = copy.deepcopy(update_secnumber)
122116

123117
# now iterate over env.toc_secnumbers to ensure all secnumbers are updated
124118
# at the same time
125119
for docname in env.toc_secnumbers:
126120
# get the new and old secnumbers for this docname
127-
old_secnumber = env.titles_old.get(docname, {}).get(
128-
"secnumber", None
129-
)
121+
old_secnumber = env.titles_old.get(docname, {}).get("secnumber", None)
130122
new_secnumber = env.titles[docname].get("secnumber", None)
131123
renumber_depth = len(new_secnumber) if new_secnumber else 0
132124
# iterate over all anchors in this docname
@@ -147,9 +139,7 @@ def assign_section_numbers(self, env):
147139
secnumber[i] == old_secnumber[i]
148140
): # only if the old matches the current
149141
update_secnumber[i] = new_secnumber[i]
150-
env.toc_secnumbers[doc][anchor] = copy.deepcopy(
151-
update_secnumber
152-
)
142+
env.toc_secnumbers[doc][anchor] = copy.deepcopy(update_secnumber)
153143

154144
# Now, convert all secnumbers in toc_secnumbers to tuples
155145
# to avoid issues with other steps in the algorithm
@@ -158,19 +148,15 @@ def assign_section_numbers(self, env):
158148
if not secnumber:
159149
continue
160150
secnumber = (*secnumber,) # convert to tuple
161-
env.toc_secnumbers[docname][anchorname] = copy.deepcopy(
162-
secnumber
163-
)
151+
env.toc_secnumbers[docname][anchorname] = copy.deepcopy(secnumber)
164152
return result
165153

166154
def __renumber(self, number_set, style_set):
167155
if not number_set or not style_set:
168156
return number_set
169157

170158
if not isinstance(style_set, list):
171-
style_set = [
172-
style_set
173-
] # if not multiple styles are given, convert to list
159+
style_set = [style_set] # if not multiple styles are given, convert to list
174160
# for each style, convert the corresponding number, where only the first number
175161
# is rebased, the rest are kept as is, but converted.
176162
# convert the first number to the new style
@@ -262,9 +248,7 @@ def __fix_nested_toc(self, env, toctree, style):
262248

263249
if "secnumber" not in env.titles[ref]:
264250
continue
265-
new_secnumber = self.__renumber(
266-
env.titles[ref]["secnumber"], style
267-
)
251+
new_secnumber = self.__renumber(env.titles[ref]["secnumber"], style)
268252
env.titles[ref]["secnumber"] = copy.deepcopy(new_secnumber)
269253
if ref in env.tocs:
270254
self.__replace_toc(env, ref, env.tocs[ref], style)

sphinx_external_toc/events.py

Lines changed: 14 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -40,9 +40,7 @@ def create_warning(
4040
message = f"{message} [{wtype}.{category}]"
4141
kwargs = {"line": line} if line is not None else {}
4242

43-
if not logging.is_suppressed_warning(
44-
wtype, category, app.config.suppress_warnings
45-
):
43+
if not logging.is_suppressed_warning(wtype, category, app.config.suppress_warnings):
4644
msg_node = doctree.reporter.warning(message, **kwargs)
4745
if append_to is not None:
4846
append_to.append(msg_node)
@@ -70,13 +68,9 @@ def parse_toc_to_env(app: Sphinx, config: Config) -> None:
7068
else:
7169
path = Path(str(external_toc_path))
7270
if not path.exists():
73-
raise ExtensionError(
74-
f"[etoc] `external_toc_path` does not exist: {path}"
75-
)
71+
raise ExtensionError(f"[etoc] `external_toc_path` does not exist: {path}")
7672
if not path.is_file():
77-
raise ExtensionError(
78-
f"[etoc] `external_toc_path` is not a file: {path}"
79-
)
73+
raise ExtensionError(f"[etoc] `external_toc_path` is not a file: {path}")
8074
try:
8175
site_map = parse_toc_yaml(path)
8276
except Exception as exc:
@@ -117,24 +111,17 @@ def parse_toc_to_env(app: Sphinx, config: Config) -> None:
117111
for i in range(len(components))
118112
)
119113
# don't exclude docnames matching globs
120-
or any(
121-
patmatch(posix_no_suffix, pat)
122-
for pat in site_map.globs()
123-
)
114+
or any(patmatch(posix_no_suffix, pat) for pat in site_map.globs())
124115
):
125116
new_excluded.append(posix)
126117
if new_excluded:
127118
logger.info(
128119
"[etoc] Excluded %s extra file(s) not in toc",
129120
len(new_excluded),
130121
)
131-
logger.debug(
132-
"[etoc] Excluded extra file(s) not in toc: %r", new_excluded
133-
)
122+
logger.debug("[etoc] Excluded extra file(s) not in toc: %r", new_excluded)
134123
# Note, don't `extend` list, as it alters the default `Config.config_values`
135-
config["exclude_patterns"] = (
136-
config["exclude_patterns"] + new_excluded
137-
)
124+
config["exclude_patterns"] = config["exclude_patterns"] + new_excluded
138125

139126

140127
def add_changed_toctrees(
@@ -153,9 +140,7 @@ def add_changed_toctrees(
153140
if not previous_map:
154141
return set()
155142
filenames = site_map.get_changed(previous_map)
156-
return {
157-
remove_suffix(name, app.config.source_suffix) for name in filenames
158-
}
143+
return {remove_suffix(name, app.config.source_suffix) for name in filenames}
159144

160145

161146
class TableOfContentsNode(nodes.Element):
@@ -248,9 +233,7 @@ def insert_toctrees(app: Sphinx, doctree: nodes.document) -> None:
248233
# TODO this wasn't in the original code,
249234
# but alabaster theme intermittently raised `KeyError('rawcaption')`
250235
subnode["rawcaption"] = toctree.caption or ""
251-
subnode["glob"] = any(
252-
isinstance(entry, GlobItem) for entry in toctree.items
253-
)
236+
subnode["glob"] = any(isinstance(entry, GlobItem) for entry in toctree.items)
254237
subnode["hidden"] = False if toc_placeholders else toctree.hidden
255238
subnode["includehidden"] = False
256239
subnode["numbered"] = (
@@ -281,9 +264,7 @@ def insert_toctrees(app: Sphinx, doctree: nodes.document) -> None:
281264
else:
282265
message = f"toctree contains reference to nonexisting document {docname!r}"
283266

284-
create_warning(
285-
app, doctree, "ref", message, append_to=node_list
286-
)
267+
create_warning(app, doctree, "ref", message, append_to=node_list)
287268
app.env.note_reread()
288269
else:
289270
subnode["entries"].append((title, docname))
@@ -297,10 +278,10 @@ def insert_toctrees(app: Sphinx, doctree: nodes.document) -> None:
297278
subnode["entries"].append((None, docname))
298279
subnode["includefiles"].append(docname)
299280
if not docnames:
300-
message = f"toctree glob pattern '{entry}' didn't match any documents"
301-
create_warning(
302-
app, doctree, "glob", message, append_to=node_list
281+
message = (
282+
f"toctree glob pattern '{entry}' didn't match any documents"
303283
)
284+
create_warning(app, doctree, "glob", message, append_to=node_list)
304285

305286
# reversing entries can be useful when globbing
306287
if toctree.reversed:
@@ -358,10 +339,6 @@ def ensure_index_file(app: Sphinx, exception: Optional[Exception]) -> None:
358339
# Assume a single index for all non dir-HTML builders
359340
redirect_url = f"{root_name}.html"
360341

361-
redirect_text = (
362-
f'<meta http-equiv="Refresh" content="0; url={redirect_url}" />\n'
363-
)
342+
redirect_text = f'<meta http-equiv="Refresh" content="0; url={redirect_url}" />\n'
364343
index_path.write_text(redirect_text, encoding="utf8")
365-
logger.info(
366-
"[etoc] missing index.html written as redirect to '%s.html'", root_name
367-
)
344+
logger.info("[etoc] missing index.html written as redirect to '%s.html'", root_name)

0 commit comments

Comments
 (0)