Skip to content

Commit cf59a34

Browse files
committed
Speed up snippet pattern matching
1 parent fc00b98 commit cf59a34

File tree

1 file changed

+18
-4
lines changed

1 file changed

+18
-4
lines changed

sphinxnotes/snippet/ext.py

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,17 @@ def extract_keywords(s:Snippet) -> List[str]:
6060
return keywords
6161

6262

63-
def is_matched(pats:Dict[str,List[str]], s:[Snippet], docname:str) -> bool:
63+
def is_document_matched(pats:Dict[str,List[str]], docname:str) -> Dict[str,List[str]]:
64+
"""Whether the docname matched by given patterns pats"""
65+
new_pats = {}
66+
for tag, ps in pats.items():
67+
for pat in ps:
68+
if re.match(pat, docname):
69+
new_pats.setdefault(tag, []).append(pat)
70+
return new_pats
71+
72+
73+
def is_snippet_matched(pats:Dict[str,List[str]], s:[Snippet], docname:str) -> bool:
6474
"""Whether the snippet's tags and docname matched by given patterns pats"""
6575
if '*' in pats: # Wildcard
6676
for pat in pats['*']:
@@ -100,11 +110,15 @@ def on_doctree_resolved(app:Sphinx, doctree:nodes.document, docname:str) -> None
100110
logger.debug('[snippet] node %s is not nodes.document', type(doctree), location=doctree)
101111
return
102112

103-
pats = app.config.snippet_patterns
113+
pats = is_document_matched(app.config.snippet_patterns, docname)
114+
if len(pats) == 0:
115+
logger.debug('[snippet] skip picking because %s is not matched', docname)
116+
return
117+
104118
doc = []
105119
snippets = pick(doctree)
106120
for s, n in snippets:
107-
if not is_matched(pats, s, docname):
121+
if not is_snippet_matched(pats, s, docname):
108122
continue
109123
doc.append(Item(snippet=s,
110124
tags=extract_tags(s),
@@ -130,7 +144,7 @@ def setup(app:Sphinx):
130144
app.add_builder(Builder)
131145

132146
app.add_config_value('snippet_config', {}, '')
133-
app.add_config_value('snippet_patterns', {'*':'.*'}, '')
147+
app.add_config_value('snippet_patterns', {'*':['.*']}, '')
134148

135149
app.connect('config-inited', on_config_inited)
136150
app.connect('env-get-outdated', on_env_get_outdated)

0 commit comments

Comments
 (0)