Skip to content

Commit 6fc300d

Browse files
committed
refactor: Move extension entrypoint from ext.py to __init__.py
Then it can be consistency with other sphinxnotes projects.
1 parent 8f80425 commit 6fc300d

File tree

4 files changed

+64
-23
lines changed

4 files changed

+64
-23
lines changed

docs/conf.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,7 @@
152152
# add these directories to sys.path here. If the directory is relative to the
153153
# documentation root, use os.path.abspath to make it absolute, like shown here.
154154
sys.path.insert(0, os.path.abspath('../src/sphinxnotes'))
155-
extensions.append('snippet.ext')
155+
extensions.append('snippet')
156156

157157
# DOG FOOD CONFIGURATION START
158158

src/sphinxnotes/snippet/__init__.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
"""
2+
sphinxnotes.snippet
3+
~~~~~~~~~~~~~~~~~~~
4+
5+
Sphinx extension entrypoint.
6+
7+
:copyright: Copyright 2024 Shengyu Zhang
8+
:license: BSD, see LICENSE for details.
9+
"""
10+
11+
12+
def setup(app):
13+
# **WARNING**: We don't import these packages globally, because the current
14+
# package (sphinxnotes.snippet) is always resloved when importing
15+
# sphinxnotes.snippet.*. If we import packages here, eventually we will
16+
# load a lot of packages from the Sphinx. It will seriously **SLOW DOWN**
17+
# the startup time of our CLI tool (sphinxnotes.snippet.cli).
18+
#
19+
# .. seealso:: https://github.com/sphinx-notes/snippet/pull/31
20+
from .ext import (
21+
SnippetBuilder,
22+
on_config_inited,
23+
on_env_get_outdated,
24+
on_doctree_resolved,
25+
on_builder_finished,
26+
)
27+
28+
app.add_builder(SnippetBuilder)
29+
30+
app.add_config_value('snippet_config', {}, '')
31+
app.add_config_value('snippet_patterns', {'*': ['.*']}, '')
32+
33+
app.connect('config-inited', on_config_inited)
34+
app.connect('env-get-outdated', on_env_get_outdated)
35+
app.connect('doctree-resolved', on_doctree_resolved)
36+
app.connect('build-finished', on_builder_finished)

src/sphinxnotes/snippet/cli.py

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,15 @@
22
sphinxnotes.snippet.cli
33
~~~~~~~~~~~~~~~~~~~~~~~
44
5-
:copyright: Copyright 2020 Shengyu Zhang
5+
Command line entrypoint.
6+
7+
:copyright: Copyright 2024 Shengyu Zhang
68
:license: BSD, see LICENSE for details.
79
"""
810

11+
# **NOTE**: Import new packages with caution:
12+
# Importing complex packages (like sphinx.*) will directly slow down the
13+
# startup of the CLI tool.
914
from __future__ import annotations
1015
import sys
1116
import argparse
@@ -14,10 +19,8 @@
1419
from textwrap import dedent
1520
from shutil import get_terminal_size
1621
import posixpath
17-
from importlib.metadata import version
1822

1923
from xdg.BaseDirectory import xdg_config_home
20-
from sphinx.util.matching import patmatch
2124

2225
from .snippets import Document
2326
from .config import Config
@@ -40,7 +43,7 @@ def get_integration_file(fn: str) -> str:
4043
.. seealso::
4144
4245
see ``[tool.setuptools.package-data]`` section of pyproject.toml to know
43-
how files are included.
46+
how files are included.
4447
"""
4548
# TODO: use https://docs.python.org/3/library/importlib.resources.html#importlib.resources.files
4649
prefix = path.abspath(path.dirname(__file__))
@@ -62,10 +65,11 @@ def main(argv: List[str] = sys.argv[1:]):
6265
* (any) wildcard for any snippet"""),
6366
)
6467
parser.add_argument(
65-
'-v',
6668
'--version',
67-
action='version',
68-
version='%(prog)s ' + version('sphinxnotes.any'),
69+
# add_argument provides action='version', but it requires a version
70+
# literal and doesn't support lazily obtaining version.
71+
action='store_true',
72+
help="show program's version number and exit",
6973
)
7074
parser.add_argument(
7175
'-c', '--config', default=DEFAULT_CONFIG_FILE, help='path to configuration file'
@@ -180,6 +184,16 @@ def main(argv: List[str] = sys.argv[1:]):
180184
# Parse command line arguments
181185
args = parser.parse_args(argv)
182186

187+
# Print version message.
188+
# See parser.add_argument('--version', ...) for more detais.
189+
if args.version:
190+
# NOTE: Importing is slow, do it on demand.
191+
from importlib.metadata import version
192+
193+
pkgname = 'sphinxnotes.snippet'
194+
print(pkgname, version(pkgname))
195+
parser.exit()
196+
183197
# Load config from file
184198
if args.config == DEFAULT_CONFIG_FILE and not path.isfile(DEFAULT_CONFIG_FILE):
185199
print(
@@ -223,6 +237,9 @@ def _on_command_stat(args: argparse.Namespace):
223237
def _filter_list_items(
224238
cache: Cache, tags: str, docname_glob: str
225239
) -> Iterable[Tuple[IndexID, Index]]:
240+
# NOTE: Importing is slow, do it on demand.
241+
from sphinx.util.matching import patmatch
242+
226243
for index_id, index in cache.indexes.items():
227244
# Filter by tags.
228245
if index[0] not in tags and '*' not in tags:

src/sphinxnotes/snippet/ext.py

Lines changed: 3 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
"""
2-
sphinxnotes.ext.snippet
2+
sphinxnotes.snippet.ext
33
~~~~~~~~~~~~~~~~~~~~~~~
44
5-
Sphinx extension for sphinxnotes.snippet.
5+
Sphinx extension implementation, but the entrypoint is located at __init__.py.
66
7-
:copyright: Copyright 2021 Shengyu Zhang
7+
:copyright: Copyright 2024 Shengyu Zhang
88
:license: BSD, see LICENSE for details.
99
"""
1010

@@ -206,15 +206,3 @@ def _format_modified_time(timestamp: float) -> str:
206206
"""Return an RFC 3339 formatted string representing the given timestamp."""
207207
seconds, fraction = divmod(timestamp, 1)
208208
return time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(seconds)) + f'.{fraction:.3f}'
209-
210-
211-
def setup(app: Sphinx):
212-
app.add_builder(SnippetBuilder)
213-
214-
app.add_config_value('snippet_config', {}, '')
215-
app.add_config_value('snippet_patterns', {'*': ['.*']}, '')
216-
217-
app.connect('config-inited', on_config_inited)
218-
app.connect('env-get-outdated', on_env_get_outdated)
219-
app.connect('doctree-resolved', on_doctree_resolved)
220-
app.connect('build-finished', on_builder_finished)

0 commit comments

Comments
 (0)