Skip to content

Commit 518a727

Browse files
committed
linting
1 parent 32fa15e commit 518a727

File tree

5 files changed

+128
-54
lines changed

5 files changed

+128
-54
lines changed

docs/Makefile

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,14 @@ examples:
2121
@mkdir -p tmp
2222
${RUN} bin/example_pages.py --indir _posts/plotly_js --outdir tmp/javascript --verbose 1
2323

24+
## format: reformat Python code
25+
format:
26+
@ruff format bin
27+
28+
## lint: check code and project
29+
lint:
30+
@ruff check bin
31+
2432
## reference: build reference documentation in ./tmp
2533
reference:
2634
@rm -rf tmp

docs/bin/example_pages.py

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,10 @@
77
from pathlib import Path
88
import re
99

10-
from utils import _log, _str
10+
from utils import _log
1111

1212

13-
HTML_TAG_RE = re.compile(r'<[^>]*>')
13+
HTML_TAG_RE = re.compile(r"<[^>]*>")
1414
SUITE_RE = re.compile(r'where:"suite","(.+?)"')
1515

1616

@@ -57,10 +57,10 @@ def _make_html(examples):
5757

5858
accum.append(' <div class="row">\n')
5959
accum.append(_make_html_text(path, header, content))
60-
accum.append(' </div>\n')
60+
accum.append(" </div>\n")
6161

62-
accum.append(' </div>\n')
63-
accum.append('</div>\n\n')
62+
accum.append(" </div>\n")
63+
accum.append("</div>\n\n")
6464

6565
return "".join(accum)
6666

@@ -73,13 +73,15 @@ def _make_html(examples):
7373
</div>
7474
"""
7575

76+
7677
def _make_html_name(path, header):
7778
"""Make example name block."""
7879
name = header["name"] if header["name"] else ""
7980
_log(not name, f"{path} does not have name")
8081
name = _strip_html(name.replace(" ", "-").replace(",", "").lower())
8182
return HTML_NAME.format(name=name)
8283

84+
8385
HTML_TEXT = """\
8486
<div class="{columns} columns">
8587
{markdown_content}
@@ -100,11 +102,14 @@ def _make_html_name(path, header):
100102
</blockquote>
101103
"""
102104

105+
103106
def _make_html_text(path, header, content):
104107
"""Make text of example."""
105108
columns = "twelve" if "horizontal" in header.get("arrangement", "") else "six"
106109
markdown_content = markdown(header.get("markdown_content", ""))
107-
page_content = HTML_TEXT_PAGE_CONTENT.format(text=escape(content)) if content else ""
110+
page_content = (
111+
HTML_TEXT_PAGE_CONTENT.format(text=escape(content)) if content else ""
112+
)
108113
description = header.get("description", "")
109114
description = HTML_TEXT_DESCRIPTION.format(text=description) if description else ""
110115
return HTML_TEXT.format(
@@ -121,7 +126,9 @@ def _parse_args():
121126
parser.add_argument("--indir", type=Path, help="Input directory")
122127
parser.add_argument("--schema", type=Path, help="Path to plot schema JSON file")
123128
parser.add_argument("--outdir", type=Path, help="Output directory")
124-
parser.add_argument("--verbose", type=int, default=0, help="Integer verbosity level")
129+
parser.add_argument(
130+
"--verbose", type=int, default=0, help="Integer verbosity level"
131+
)
125132
return parser.parse_args()
126133

127134

@@ -131,10 +138,13 @@ def _process(args, path, record, example_files):
131138
return
132139

133140
examples = [
134-
(p, r) for p, r in example_files.items()
141+
(p, r)
142+
for p, r in example_files.items()
135143
if r["header"].get("suite", None) == suite
136144
]
137-
examples.sort(key=lambda pair: (example_files[pair[0]]["header"]["order"], str(pair[0])))
145+
examples.sort(
146+
key=lambda pair: (example_files[pair[0]]["header"]["order"], str(pair[0]))
147+
)
138148

139149
section = record["header"]["permalink"].strip("/").split("/")[-1]
140150
_log(args.verbose > 0, f"...{section}: {len(examples)}")

docs/bin/reference_pages.py

Lines changed: 71 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
"""
2929

3030
PLOT_SCHEMA_REPLACEMENTS = (
31-
('*', '"'),
31+
("*", '"'),
3232
("{array}", "array"),
3333
("{arrays}", "arrays"),
3434
("{object}", "object"),
@@ -49,8 +49,7 @@
4949
"magic_underscores",
5050
"role",
5151
"stream",
52-
"transforms"
53-
"uid",
52+
"transformsuid",
5453
}
5554

5655
SKIP_MUSTMATCH = {
@@ -70,12 +69,14 @@
7069
"yaxis",
7170
}
7271

73-
ANNOTATION = " ".join([
74-
"<br>An annotation is a text element that can be placed anywhere in the plot.",
75-
"It can be positioned with respect to relative coordinates in the plot",
76-
"or with respect to the actual data coordinates of the graph.",
77-
"Annotations can be shown with or without an arrow.",
78-
])
72+
ANNOTATION = " ".join(
73+
[
74+
"<br>An annotation is a text element that can be placed anywhere in the plot.",
75+
"It can be positioned with respect to relative coordinates in the plot",
76+
"or with respect to the actual data coordinates of the graph.",
77+
"Annotations can be shown with or without an arrow.",
78+
]
79+
)
7980

8081

8182
def main():
@@ -93,23 +94,37 @@ def main():
9394
continue
9495
title = m.group(1)
9596

96-
if (m := INCLUDE_TRACE_RE.search(src_content)):
97-
if _log(m.group(1) != title, f"title {title} != include title {m.group(1)} in {src_path}"):
97+
if m := INCLUDE_TRACE_RE.search(src_content):
98+
if _log(
99+
m.group(1) != title,
100+
f"title {title} != include title {m.group(1)} in {src_path}",
101+
):
98102
continue
99103
trace_name = m.group(2)
100104
trace_data = schema["traces"].get(trace_name, None)
101-
if _log(trace_data is None, f"trace '{trace_name}' not found in {args.schema}"):
105+
if _log(
106+
trace_data is None, f"trace '{trace_name}' not found in {args.schema}"
107+
):
102108
continue
103109
html = _reference_trace(args, schema, src_path, trace_name, trace_data)
104110

105-
elif (m := INCLUDE_BLOCK_RE.search(src_content)):
111+
elif m := INCLUDE_BLOCK_RE.search(src_content):
106112
parent_link = m.group(1)
107113
block = m.group(2)
108114
parent_path = m.group(3)
109115
mustmatch = m.group(4)
110116
accum = []
111117
attributes = schema["layout"]["layoutAttributes"]
112-
_reference_block(args, src_path, accum, attributes, parent_link, parent_path, block, mustmatch)
118+
_reference_block(
119+
args,
120+
src_path,
121+
accum,
122+
attributes,
123+
parent_link,
124+
parent_path,
125+
block,
126+
mustmatch,
127+
)
113128
html = _replace_special("".join([_str(a) for a in accum]))
114129

115130
else:
@@ -144,15 +159,21 @@ def _get(value, key, default=None):
144159

145160
def _parse_args():
146161
"""Parse command-line arguments."""
147-
parser = argparse.ArgumentParser(description="Generate HTML reference documentation")
162+
parser = argparse.ArgumentParser(
163+
description="Generate HTML reference documentation"
164+
)
148165
parser.add_argument("inputs", nargs="+", type=Path, help="Input Jekyll files")
149166
parser.add_argument("--schema", type=Path, help="Path to plot schema JSON file")
150167
parser.add_argument("--outdir", type=Path, help="Output directory")
151-
parser.add_argument("--verbose", type=int, default=0, help="Integer verbosity level")
168+
parser.add_argument(
169+
"--verbose", type=int, default=0, help="Integer verbosity level"
170+
)
152171
return parser.parse_args()
153172

154173

155-
def _reference_block(args, src_path, accum, attributes, parent_link, parent_path, block, mustmatch=None):
174+
def _reference_block(
175+
args, src_path, accum, attributes, parent_link, parent_path, block, mustmatch=None
176+
):
156177
"""Generate HTML documentation for a trace's attributes."""
157178
accum.append("<ul>\n")
158179
for key, value in attributes.items():
@@ -168,7 +189,9 @@ def _reference_block(args, src_path, accum, attributes, parent_link, parent_path
168189
accum.append(f" {key}\n")
169190
accum.append("</a>\n")
170191

171-
accum.append(f"<br><em>Parent:</em> <code>{parent_path.replace('-', '.')}</code>\n")
192+
accum.append(
193+
f"<br><em>Parent:</em> <code>{parent_path.replace('-', '.')}</code>\n"
194+
)
172195

173196
if (key == "type") and (block == "data"):
174197
accum.append("<br />\n")
@@ -183,13 +206,17 @@ def _reference_block(args, src_path, accum, attributes, parent_link, parent_path
183206
if _get(value, "items") and (_get(value, "valType") != "info_array"):
184207
_reference_block_array(src_path, accum, key, value)
185208
elif _get(value, "role") == "object":
186-
accum.append('<br><em>Type:</em> {object} containing one or more of the keys listed below.\n')
209+
accum.append(
210+
"<br><em>Type:</em> {object} containing one or more of the keys listed below.\n"
211+
)
187212

188213
if _get(value, "description", "") != "":
189214
accum.append(f"<p>{escape(value.get('description'))}</p>\n")
190215

191216
if _get(value, "role") == "object":
192-
_reference_block_object(args, src_path, accum, parent_link, parent_path, key, value)
217+
_reference_block_object(
218+
args, src_path, accum, parent_link, parent_path, key, value
219+
)
193220

194221
accum.append("</li>\n")
195222
accum.append("</ul>\n")
@@ -201,11 +228,13 @@ def _reference_block_valtype(src_path, accum, key, value):
201228
inner = " " * 20
202229
accum.append("<br>\n")
203230

204-
if (_get(value, "valType") == "enumerated") or _get(_get(value, "valType"), "values"):
231+
if (_get(value, "valType") == "enumerated") or _get(
232+
_get(value, "valType"), "values"
233+
):
205234
accum.append(f"{outer}<em>Type:</em>\n")
206235
accum.append(f"{inner}{_get(value, 'valType')}")
207236
if _get(value, "arrayOk"):
208-
accum.append(f" or array of { _get(value, 'valType')}s\n")
237+
accum.append(f" or array of {_get(value, 'valType')}s\n")
209238
accum.append(f"{inner}, one of (\n")
210239
for i, sub_value in enumerate(_get(value, "values")):
211240
_comma(accum, i, "|")
@@ -217,7 +246,9 @@ def _reference_block_valtype(src_path, accum, key, value):
217246
if _get(value, "arrayOk"):
218247
accum.append(f" or array of {_get(value, 'valType')}s")
219248
if _get(value, "min") and _get(value, "max"):
220-
accum.append(f" between or equal to {_get(value, 'min')} and {_get(value, 'max')}\n")
249+
accum.append(
250+
f" between or equal to {_get(value, 'min')} and {_get(value, 'max')}\n"
251+
)
221252
elif _get(value, "min"):
222253
accum.append(f" greater than or equal to {_get(value, 'min')}\n")
223254
elif _get(value, "max"):
@@ -278,7 +309,7 @@ def _reference_block_valtype(src_path, accum, key, value):
278309
return
279310
accum.append(f"{inner}<em>Type:</em> string")
280311
if _get(value, "arrayOk"):
281-
accum.append(f" or array of strings")
312+
accum.append(" or array of strings")
282313

283314
else:
284315
accum.append(f"{inner}<em>Type:</em> {_get(value, 'valType')}\n")
@@ -293,7 +324,6 @@ def _reference_block_valtype(src_path, accum, key, value):
293324
def _reference_block_dflt(src_path, accum, key, value):
294325
"""Handle a default."""
295326
outer = " " * 16
296-
inner = " " * 20
297327
if _get(value, "valType") == "flaglist":
298328
accum.append(
299329
f"{outer}<br><em>Default:</em> <code>*{_get(value, 'dflt')}*</code>\n"
@@ -307,9 +337,13 @@ def _reference_block_dflt(src_path, accum, key, value):
307337
accum.append(f"[{', '.join(temp)}]")
308338
elif _get(value, "valType") in {"info_array", "colorlist"}:
309339
accum.append(f"[{', '.join([_str(x) for x in _get(value, 'dflt')])}]")
310-
elif (_get(value, "valType") in {"string", "color"}) or (_get(value, "dflt") == "auto"):
340+
elif (_get(value, "valType") in {"string", "color"}) or (
341+
_get(value, "dflt") == "auto"
342+
):
311343
accum.append(f"*{_get(value, 'dflt')}*")
312-
elif (_get(value, "valType") == "enumerated") and (_get(value, "dflt") not in {"true", "false"}):
344+
elif (_get(value, "valType") == "enumerated") and (
345+
_get(value, "dflt") not in {"true", "false"}
346+
):
313347
accum.append(f"*{_get(value, 'dflt')}*")
314348
else:
315349
accum.append(_get(value, "dflt"))
@@ -327,19 +361,21 @@ def _reference_block_array(src_path, accum, key, value):
327361
accum.append(f"{inner}{ANNOTATION}\n")
328362

329363

330-
def _reference_block_object(args, src_path, accum, parent_link, parent_path, key, value):
364+
def _reference_block_object(
365+
args, src_path, accum, parent_link, parent_path, key, value
366+
):
331367
"""Handle an object with a recursive call."""
332-
local_parent_link = f"{parent_link}-{key}"
333-
local_parent_path = f"{parent_path}-{key}"
368+
parent_path = f"{parent_path}-{key}"
334369
if _get(value, "items"):
335370
# This will break if there is ever more than one type of item in items,
336371
# but for now it's just "shape" and "annotation"
337372
for item_key, item_value in _get(value, "items").items():
338373
attributes = item_value
339-
local_parent_link = f"{parent_link}-{key}-items-{item_key}"
340374
else:
341375
attributes = value
342-
_reference_block(args, src_path, accum, attributes, parent_link, parent_path, "nested")
376+
_reference_block(
377+
args, src_path, accum, attributes, parent_link, parent_path, "nested"
378+
)
343379

344380

345381
def _reference_trace(args, schema, src_path, trace_name, trace_data):
@@ -354,7 +390,9 @@ def _reference_trace(args, schema, src_path, trace_name, trace_data):
354390
parent_link = trace_name
355391
parent_path = f"data[type={trace_name}]"
356392
attributes = trace_data["attributes"]
357-
_reference_block(args, src_path, accum, attributes, parent_link, parent_path, "data")
393+
_reference_block(
394+
args, src_path, accum, attributes, parent_link, parent_path, "data"
395+
)
358396

359397
return _replace_special("".join([_str(a) for a in accum]))
360398

@@ -377,16 +415,5 @@ def _skip_mustmatch(key, mustmatch):
377415
return False
378416

379417

380-
def _str(val):
381-
"""Hacky string conversion."""
382-
if isinstance(val, str):
383-
return val
384-
if isinstance(val, bool):
385-
return str(val).lower()
386-
if isinstance(val, int):
387-
return str(val)
388-
return str(val)
389-
390-
391418
if __name__ == "__main__":
392419
main()

pyproject.toml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,5 +5,6 @@ version = "3.1.0"
55
requires-python = ">=3.12"
66
dependencies = [
77
"markdown",
8-
"python-frontmatter"
8+
"python-frontmatter",
9+
"ruff"
910
]

0 commit comments

Comments
 (0)