Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions Wrapping/Generators/Doc/doxy2swig.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ def do_compounddef(self, node):
for n in names:
if n in first:
self.parse(first[n])
self.add_text(['";', "\n"])
self.end_docstring()
for n in node.childNodes:
if n not in first.values():
self.parse(n)
Expand Down Expand Up @@ -290,7 +290,10 @@ def do_memberdef(self, node):
for n in node.childNodes:
if n not in first.values():
self.parse(n)
self.add_text(['";', "\n"])
self.end_docstring()

def end_docstring(self):
self.add_text(['";', "\n"])

def do_definition(self, node):
data = node.firstChild.data
Expand Down
76 changes: 73 additions & 3 deletions Wrapping/Generators/Doc/itk_doxy2swig.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,78 @@
import glob
from doxy2swig import *
from io import StringIO
from xml.dom import minidom

CITE_REFID_PREFIX = "citelist_1CITEREF_"
_bibliographies = {}


def _plain_text(node):
if node.nodeType == node.TEXT_NODE:
return node.data
if node.nodeType != node.ELEMENT_NODE:
return ""
if node.tagName == "nonbreakablespace":
return " "
if node.tagName in ("ndash", "mdash"):
return "-"
text = "".join(_plain_text(n) for n in node.childNodes)
if node.tagName == "ulink":
text += f" ({node.getAttribute('url')})"
return text


def _bibliography(xml_dir):
"""Map citation refids to the entries of Doxygen's citelist.xml."""
if xml_dir not in _bibliographies:
entries = {}
citelist = os.path.join(xml_dir, "citelist.xml")
if os.path.isfile(citelist):
doc = minidom.parse(citelist)
for variablelist in doc.getElementsByTagName("variablelist"):
refid = None
for child in variablelist.childNodes:
if child.nodeType != child.ELEMENT_NODE:
continue
if child.tagName == "varlistentry":
anchors = child.getElementsByTagName("anchor")
refid = anchors[0].getAttribute("id") if anchors else None
elif child.tagName == "listitem" and refid:
entries[refid] = " ".join(_plain_text(child).split())
Comment thread
dzenanz marked this conversation as resolved.
Resolved
refid = None
_bibliographies[xml_dir] = entries
return _bibliographies[xml_dir]


class itkDoxy2SWIG(Doxy2SWIG):
def __init__(self, src, cpp_name="", swig_name=""):
Doxy2SWIG.__init__(self, src)
self.cpp_name = cpp_name
self.swig_name = swig_name
self.citations = []

def do_ref(self, node):
refid = node.getAttribute("refid")
if not refid.startswith(CITE_REFID_PREFIX):
Doxy2SWIG.do_ref(self, node)
return
# Doxygen's [N] labels only index its own bibliography page, and
# without bibtex Doxygen writes the key instead.
self.add_text(" " + refid[len(CITE_REFID_PREFIX) :])
if refid not in self.citations:
self.citations.append(refid)

def end_docstring(self):
bibliography = _bibliography(self.my_dir)
references = [r for r in self.citations if r in bibliography]
if references:
self.add_text(["\n", "\n", "References:", "\n"])
for refid in references:
entry = f"{refid[len(CITE_REFID_PREFIX) :]}: {bibliography[refid]}"
entry = entry.replace("\\", r"\\\\").replace('"', r"\"")
self.add_text(["\n", entry, "\n"])
self.citations = []
Doxy2SWIG.end_docstring(self)

def write_to_file(self, file):
if self.multi:
Expand Down Expand Up @@ -93,7 +158,7 @@ def do_memberdef(self, node):
# restore the old self.pieces
self.pieces = pieces_backup
else:
self.add_text(['";', "\n"])
self.end_docstring()


def d2s_dir(in_dir_name, out_swig_i):
Expand All @@ -117,9 +182,14 @@ def d2s_dir(in_dir_name, out_swig_i):
output.write(tpl.replace("@[{(]})@", swig_name))
else:
print(f"Warning: {xfn} does not exist. Ignore it.", file=sys.stderr)
text = output.getvalue()
# An unchanged file keeps its timestamp, so the build skips SWIG for it.
if os.path.isfile(out_swig_i):
with open(out_swig_i, encoding="utf-8") as f:
if f.read() == text:
return
with open(out_swig_i, "w", encoding="utf-8") as f:
f.write(output.getvalue())
f.close()
f.write(text)


def main(in_dir_name, out_swig_i):
Expand Down
7 changes: 7 additions & 0 deletions Wrapping/Generators/Python/Tests/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -333,3 +333,10 @@ itk_python_add_test(
${CMAKE_CURRENT_SOURCE_DIR}/pyi_generator_merge_test.py
${CMAKE_CURRENT_SOURCE_DIR}/../itk/pyi_generator.py
)

itk_python_add_test(
NAME PythonDoxy2SwigCitationTest
COMMAND
${CMAKE_CURRENT_SOURCE_DIR}/doxy2swig_citation_test.py
${CMAKE_CURRENT_SOURCE_DIR}/../../Doc
)
79 changes: 79 additions & 0 deletions Wrapping/Generators/Python/Tests/doxy2swig_citation_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
# ==========================================================================
#
# Copyright NumFOCUS
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ==========================================================================

# Usage: doxy2swig_citation_test.py <path to Wrapping/Generators/Doc>

import os
import sys
import tempfile

sys.path.insert(0, sys.argv[1])
from itk_doxy2swig import d2s_dir

REF = '<ref refid="citelist_1CITEREF_{}" kindref="member">[{}]</ref>'
CLASS_XML = (
'<doxygen><compounddef kind="class" prot="public">'
"<compoundname>itk::Foo</compoundname><detaileddescription><para>"
f"See {REF.format('smith2000', 1)}, {REF.format('doe2001', 2)} "
f"and again {REF.format('smith2000', 1)}."
"</para></detaileddescription></compounddef></doxygen>"
)
CITELIST_XML = (
"<doxygen><compounddef><detaileddescription><para><variablelist>"
'<varlistentry><term><anchor id="citelist_1CITEREF_smith2000"/>[1]</term>'
"</varlistentry><listitem><para>A. Smith. Title. 2000.</para></listitem>"
'<varlistentry><term><anchor id="citelist_1CITEREF_doe2001"/>[2]</term>'
"</varlistentry><listitem><para>B. Doe. Other. 2001.</para></listitem>"
"</variablelist></para></detaileddescription></compounddef></doxygen>"
)


def convert(xml_dir, citelist):
"""Convert CLASS_XML in xml_dir and return the output path and its words."""
files = {"classitk_1_1Foo.xml": CLASS_XML}
if citelist:
files["citelist.xml"] = CITELIST_XML
files["itkFoo.conf"] = (
os.path.join(xml_dir, "classitk_1_1Foo.xml") + "\titk::Foo\titkFoo\n"
)
for name, text in files.items():
with open(os.path.join(xml_dir, name), "w", encoding="utf-8") as f:
f.write(text)
out = os.path.join(xml_dir, "itkFoo_doc.i")
d2s_dir(os.path.join(xml_dir, "itkFoo.conf"), out)
with open(out, encoding="utf-8") as f:
return out, " ".join(f.read().split())


with tempfile.TemporaryDirectory() as with_bib, tempfile.TemporaryDirectory() as no_bib:
out, text = convert(with_bib, citelist=True)
assert "See smith2000, doe2001 and again smith2000." in text, text
assert "[1]" not in text, text
references = (
"References: smith2000: A. Smith. Title. 2000. doe2001: B. Doe. Other. 2001."
)
assert f'{references} ";' in text, text

# Unchanged output keeps its timestamp, so SWIG does not rerun.
os.utime(out, (1e9, 1e9))
convert(with_bib, citelist=True)
assert os.path.getmtime(out) == 1e9

_, text = convert(no_bib, citelist=False)
assert "See smith2000, doe2001 and again smith2000." in text, text
assert "References:" not in text, text
5 changes: 4 additions & 1 deletion Wrapping/macro_files/itk_auto_load_submodules.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -306,11 +306,14 @@ function(generate_wrap_doc)
COMMAND
${Python3_EXECUTABLE} ${_itk_doxy2swig_py} ${_doxy2swig_config_file}
${swig_doc_interface_file}
#DEPENDS ${ITK_WRAP_DOC_DOXYGEN_XML_FILES} ${_doxy2swig_config_file} ${_itk_doxy2swig_py}
# The target orders the Doxygen run; its stamp file reruns this command
# whenever Doxygen regenerates the XML.
DEPENDS
${WRAPPER_LIBRARY_NAME}Doxygen
${CMAKE_CURRENT_BINARY_DIR}/${WRAPPER_LIBRARY_NAME}Doxygen.stamp
${_doxy2swig_config_file}
${_itk_doxy2swig_py}
${ITK_WRAP_DOC_SOURCE_DIR}/doxy2swig.py
# COMMENT "-- Wrapping library ${_each_submodule_this_module}: Generating swig interface for inline documentation."
)
endfunction()
Expand Down
Loading