Skip to content

Commit 8d6408d

Browse files
committed
apply pre-commit fixes
1 parent 9877619 commit 8d6408d

File tree

7 files changed

+84
-55
lines changed

7 files changed

+84
-55
lines changed

quartodoc/__main__.py

Lines changed: 65 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
from quartodoc import Builder, convert_inventory
1313
from pydantic import BaseModel
1414

15+
1516
def get_package_path(package_name):
1617
"""
1718
Get the path to a package installed in the current environment.
@@ -20,13 +21,16 @@ def get_package_path(package_name):
2021
lib = importlib.import_module(package_name)
2122
return lib.__path__[0]
2223
except ModuleNotFoundError:
23-
raise ModuleNotFoundError(f"Package {package_name} not found. Please install it in your environment.")
24+
raise ModuleNotFoundError(
25+
f"Package {package_name} not found. Please install it in your environment."
26+
)
2427

2528

2629
class FileInfo(BaseModel):
2730
size: int
2831
mtime: float
29-
name: str= ""
32+
name: str = ""
33+
3034

3135
class QuartoDocFileChangeHandler(PatternMatchingEventHandler):
3236
"""
@@ -35,51 +39,59 @@ class QuartoDocFileChangeHandler(PatternMatchingEventHandler):
3539

3640
# Ignore patterns for the file watcher that are not relevant to the docs
3741
py_ignore_patterns = [
38-
'*/__pycache__/*', # These are the compiled python code files which are automatically generated by Python
39-
'*/.ipynb_checkpoints/*', # This directory is created by Jupyter Notebook for auto-saving notebooks
40-
'*/.vscode/*', # If you're using Visual Studio Code, it creates this directory to store settings specific to that project.
41-
'*/.idea/*', # Similar to .vscode/, but for JetBrains IDEs like PyCharm.
42-
'*/.git/*', # i This directory is created by Git. It's not relevant to the docs.
43-
'*/venv/*', '*/env/*', '*/.env/*', # Common names for directories containing a Python virtual environment.
44-
'*/.pytest_cache/*', # This directory is created when you run Pytest.
45-
'*/.eggs/*', '*/dist/*', '*/build/*', '*/*.egg-info/*', # These are typically created when building Python packages with setuptools.
46-
'*.pyo', # These are optimized .pyc files, created when Python is run with the -O flag.
47-
'*.pyd', # This is the equivalent of a .pyc file, but for C extensions on Windows.
48-
'*/.mypy_cache/*', # This directory is created when you run mypy.
42+
"*/__pycache__/*", # These are the compiled python code files which are automatically generated by Python
43+
"*/.ipynb_checkpoints/*", # This directory is created by Jupyter Notebook for auto-saving notebooks
44+
"*/.vscode/*", # If you're using Visual Studio Code, it creates this directory to store settings specific to that project.
45+
"*/.idea/*", # Similar to .vscode/, but for JetBrains IDEs like PyCharm.
46+
"*/.git/*", # i This directory is created by Git. It's not relevant to the docs.
47+
"*/venv/*",
48+
"*/env/*",
49+
"*/.env/*", # Common names for directories containing a Python virtual environment.
50+
"*/.pytest_cache/*", # This directory is created when you run Pytest.
51+
"*/.eggs/*",
52+
"*/dist/*",
53+
"*/build/*",
54+
"*/*.egg-info/*", # These are typically created when building Python packages with setuptools.
55+
"*.pyo", # These are optimized .pyc files, created when Python is run with the -O flag.
56+
"*.pyd", # This is the equivalent of a .pyc file, but for C extensions on Windows.
57+
"*/.mypy_cache/*", # This directory is created when you run mypy.
4958
]
5059

5160
def __init__(self, callback):
52-
super().__init__(ignore_patterns=self.py_ignore_patterns, ignore_directories=True)
61+
super().__init__(
62+
ignore_patterns=self.py_ignore_patterns, ignore_directories=True
63+
)
5364
self.callback = callback
5465
self.old_file_info = FileInfo(size=-1, mtime=-1, name="")
5566

56-
57-
def get_file_info(self, path:str) -> FileInfo:
67+
def get_file_info(self, path: str) -> FileInfo:
5868
"""
5969
Get the file size and modification time.
6070
"""
61-
return FileInfo(size=os.stat(path).st_size,
62-
mtime=os.stat(path).st_mtime,
63-
name=path)
64-
65-
def is_diff(self, old:FileInfo, new:FileInfo) -> bool:
71+
return FileInfo(
72+
size=os.stat(path).st_size, mtime=os.stat(path).st_mtime, name=path
73+
)
74+
75+
def is_diff(self, old: FileInfo, new: FileInfo) -> bool:
6676
"""
6777
Check if a file has changed. Prevents duplicate events from being triggered.
6878
"""
6979
same_nm = old.name == new.name
7080
diff_sz = old.size != new.size
71-
diff_tm = (new.mtime - old.mtime) # wait 1/4 second before triggering
81+
diff_tm = new.mtime - old.mtime # wait 1/4 second before triggering
7282

73-
if diff_tm < .25: # if consequetive events are less than 1/4th of a second apart, ignore
83+
if (
84+
diff_tm < 0.25
85+
): # if consequetive events are less than 1/4th of a second apart, ignore
7486
return False
7587
elif same_nm:
7688
if diff_sz or diff_tm >= 0.25:
7789
return True
7890
else:
7991
return False
8092
else:
81-
return True
82-
93+
return True
94+
8395
def callback_if_diff(self, event):
8496
"""
8597
Call the callback if the file has changed.
@@ -92,14 +104,15 @@ def callback_if_diff(self, event):
92104

93105
@classmethod
94106
def print_event(cls, event):
95-
print(f'Rebuilding docs. Detected: {event.event_type} path : {event.src_path}')
107+
print(f"Rebuilding docs. Detected: {event.event_type} path : {event.src_path}")
96108

97109
def on_modified(self, event):
98110
self.callback_if_diff(event)
99111

100112
def on_created(self, event):
101113
self.callback_if_diff(event)
102114

115+
103116
def _enable_logs():
104117
import logging
105118
import sys
@@ -132,10 +145,29 @@ def cli():
132145

133146

134147
@click.command()
135-
@click.option("--config", default="_quarto.yml", help="Change the path to the configuration file. The default is `./_quarto.yml`")
136-
@click.option("--filter", nargs=1, default="*", help="Specify the filter to select specific files. The default is '*' which selects all files.")
137-
@click.option("--dry-run", is_flag=True, default=False, help="If set, prevents new documents from being generated.")
138-
@click.option("--watch", is_flag=True, default=False, help="If set, the command will keep running and watch for changes in the package directory.")
148+
@click.option(
149+
"--config",
150+
default="_quarto.yml",
151+
help="Change the path to the configuration file. The default is `./_quarto.yml`",
152+
)
153+
@click.option(
154+
"--filter",
155+
nargs=1,
156+
default="*",
157+
help="Specify the filter to select specific files. The default is '*' which selects all files.",
158+
)
159+
@click.option(
160+
"--dry-run",
161+
is_flag=True,
162+
default=False,
163+
help="If set, prevents new documents from being generated.",
164+
)
165+
@click.option(
166+
"--watch",
167+
is_flag=True,
168+
default=False,
169+
help="If set, the command will keep running and watch for changes in the package directory.",
170+
)
139171
@click.option("--verbose", is_flag=True, default=False, help="Enable verbose logging.")
140172
def build(config, filter, dry_run, watch, verbose):
141173
"""
@@ -160,7 +192,7 @@ def build(config, filter, dry_run, watch, verbose):
160192
pkg_path = get_package_path(builder.package)
161193
print(f"Watching {pkg_path} for changes...")
162194
observer = Observer()
163-
observer._event_queue.maxsize = 1 # the default is 0 which is infinite, and there isn't a way to set this in the constructor
195+
observer._event_queue.maxsize = 1 # the default is 0 which is infinite, and there isn't a way to set this in the constructor
164196
event_handler = QuartoDocFileChangeHandler(callback=doc_build)
165197
observer.schedule(event_handler, pkg_path, recursive=True)
166198
observer.schedule(event_handler, cfg_path, recursive=True)
@@ -173,9 +205,10 @@ def build(config, filter, dry_run, watch, verbose):
173205
finally:
174206
observer.stop()
175207
observer.join()
176-
else:
208+
else:
177209
doc_build()
178210

211+
179212
@click.command()
180213
@click.argument("config", default="_quarto.yml")
181214
@click.option("--dry-run", is_flag=True, default=False)
@@ -192,7 +225,6 @@ def interlinks(config, dry_run):
192225
return
193226

194227
for k, v in interlinks["sources"].items():
195-
196228
# TODO: user shouldn't need to include their own docs in interlinks
197229
if v["url"] == "/":
198230
continue

quartodoc/autosummary.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -358,6 +358,7 @@ def _is_valueless(obj: dc.Object):
358358

359359
# pkgdown =====================================================================
360360

361+
361362
# TODO: styles -- pkgdown, single-page, many-pages
362363
class Builder:
363364
"""Base class for building API docs.
@@ -643,9 +644,7 @@ def from_quarto_config(cls, quarto_cfg: "str | dict"):
643644

644645

645646
class BuilderPkgdown(Builder):
646-
"""Build an API in R pkgdown style.
647-
648-
"""
647+
"""Build an API in R pkgdown style."""
649648

650649
style = "pkgdown"
651650

quartodoc/builder/blueprint.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,6 @@ def _non_default_entries(el: "BaseModel"):
128128

129129
class BlueprintTransformer(PydanticTransformer):
130130
def __init__(self, get_object=None, parser="numpy"):
131-
132131
if get_object is None:
133132
loader = GriffeLoader(
134133
docstring_parser=Parser(parser),

quartodoc/interlinks.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -369,7 +369,6 @@ def from_items(cls, items: "list[EnhancedItem]"):
369369

370370
@classmethod
371371
def from_quarto_config(cls, cfg: str | dict, root_dir: str | None = None):
372-
373372
if isinstance(cfg, str):
374373
if root_dir is None:
375374
root_dir = Path(cfg).parent
@@ -391,7 +390,6 @@ def from_quarto_config(cls, cfg: str | dict, root_dir: str | None = None):
391390

392391
# load other inventories ----
393392
for doc_name, cfg in sources.items():
394-
395393
fname = doc_name + "_objects.json"
396394
inv_path = p_root / Path(cache) / fname
397395

quartodoc/inventory.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,10 @@ def _to_clean_dict(inv: soi.Inventory):
134134

135135
@dispatch
136136
def _create_inventory_item(
137-
item: Union[dc.Object, dc.Alias], uri, dispname="-", priority="1",
137+
item: Union[dc.Object, dc.Alias],
138+
uri,
139+
dispname="-",
140+
priority="1",
138141
) -> soi.DataObjStr:
139142
target = item
140143

quartodoc/tests/test_interlinks.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,6 @@ def test_ref_from_string(raw, dst):
5555

5656
@pytest.mark.parametrize("entry", spec)
5757
def test_spec_entry(invs: Inventories, entry: TestSpecEntry):
58-
5958
ref_str, text = parse_md_style_link(entry.input)
6059
ref_str = ref_str.replace("`", "%60") # weird, but matches pandoc
6160

quartodoc/validation.py

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,26 @@
1-
2-
def fmt(err:dict):
1+
def fmt(err: dict):
32
"format error messages from pydantic."
43
msg = ""
5-
if err['msg'].startswith('Discriminator'):
4+
if err["msg"].startswith("Discriminator"):
65
return msg
7-
if err['type'] == 'value_error.missing':
8-
msg += 'Missing field'
6+
if err["type"] == "value_error.missing":
7+
msg += "Missing field"
98
else:
10-
msg += err['msg'] + ':'
11-
12-
if 'loc' in err:
13-
if len(err['loc']) == 1:
9+
msg += err["msg"] + ":"
10+
11+
if "loc" in err:
12+
if len(err["loc"]) == 1:
1413
msg += f" from root level: `{err['loc'][0]}`"
15-
elif len(err['loc']) == 3:
14+
elif len(err["loc"]) == 3:
1615
msg += f" `{err['loc'][2]}` for element {err['loc'][1]} in the list for `{err['loc'][0]}`"
17-
elif len(err['loc']) == 4 and err['loc'][2] == 'Page':
16+
elif len(err["loc"]) == 4 and err["loc"][2] == "Page":
1817
msg += f" `{err['loc'][3]}` for element {err['loc'][1]} in the list for `{err['loc'][0]}`, which you need when setting `kind: page`."
19-
elif len(err['loc']) == 5:
18+
elif len(err["loc"]) == 5:
2019
msg += f" `{err['loc'][4]}` for element {err['loc'][3]} in the list for `{err['loc'][2]}` located in element {err['loc'][1]} in the list for `{err['loc'][0]}`"
21-
elif len(err['loc']) == 6 and err['loc'][4] == 'Auto':
20+
elif len(err["loc"]) == 6 and err["loc"][4] == "Auto":
2221
msg += f" `{err['loc'][5]}` for element {err['loc'][3]} in the list for `{err['loc'][2]}` located in element {err['loc'][1]} in the list for `{err['loc'][0]}`"
2322
else:
24-
return str(err) # so we can debug and include more cases
23+
return str(err) # so we can debug and include more cases
2524
else:
2625
msg += str(err)
2726
return msg

0 commit comments

Comments
 (0)