-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathconf.py
More file actions
1146 lines (963 loc) · 40.7 KB
/
Copy pathconf.py
File metadata and controls
1146 lines (963 loc) · 40.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
#
# sphynx-demo documentation build configuration file, created by
# sphinx-quickstart on Tue Aug 2 16:48:54 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
# import sys
# sys.path.insert(0, os.path.abspath('.'))
from docutils import nodes
import git
import json
import os
import os.path
import pathlib
import posixpath
import re
import requests
import shutil
import subprocess
import sys
def setup(app):
# Add property to avoid warning.
app.add_config_value("skip_python", None, "")
app.connect("doctree-resolved", replace_pathto_in_raw_html)
_PATHTO_RE = re.compile(
r"""pathto\(\s*(['"])(?P<target>[^'"]+)\1(?:\s*,\s*(?P<resource>\d+))?\s*\)"""
)
def replace_pathto_in_raw_html(app, doctree, docname):
"""
Replace pathto(...) usages inside raw HTML nodes.
Sphinx only expands ``pathto`` in Jinja templates, not in reStructuredText
document bodies. Some pages embed raw HTML and expect ``pathto('_static/...', 1)``
to resolve to the correct relative asset path. Convert those calls after the
doctree has been resolved so included documents are rewritten using the final
output page path.
"""
if app.builder.format != "html":
return
depth = docname.count("/")
prefix = "../" * depth
def repl(match):
target = match.group("target").lstrip("/")
if "://" in target or target.startswith(("#", "mailto:", "javascript:")):
return target
return posixpath.normpath(prefix + target)
for node in doctree.findall():
if node.tagname != "raw":
continue
if "html" not in node.get("format", "").split():
continue
updated = _PATHTO_RE.sub(repl, node.astext())
if updated == node.astext():
continue
node.rawsource = updated
node.children = [nodes.Text(updated)]
def download_json():
"""
Download the common theme options of eProsima readthedocs documentation.
The theme options are defined in a JSON file that is hosted in the eProsima GitHub
repository with the index of all eProsima product documentation
(https://github.com/eProsima/all-docs).
:return: dictionary.
"""
url = "https://raw.githubusercontent.com/eProsima/all-docs/master/source/_static/json/eprosima-furo.json"
ret = dict()
try:
req = requests.get(url, allow_redirects=True, timeout=10)
except requests.RequestException as e:
print(
"Failed to download the JSON with the eProsima theme."
"Request Error: {}".format(e)
)
return ret
if req.status_code != 200:
print(
"Failed to download the JSON with the eProsima theme."
"Return code: {}".format(req.status_code)
)
return ret
ret = json.loads(req.content)
return ret
def retrieve_custom_sidebar(root_dir):
"""
Generate the custom sidebar, downloading necessary custom files.
Custom files are hosted in the eProsima GitHub repository with the index of all eProsima product documentation
(https://github.com/eProsima/all-docs).
:return: Custom sidebars if the file was downloaded and generated successfully.
Readthedocs default ones if not.
"""
url = "https://raw.githubusercontent.com/eProsima/all-docs/master/source/_templates/sidebar/commercial-support.html"
url_img = "https://raw.githubusercontent.com/eProsima/all-docs/master/source/_static/eprosima-logo-white.png"
ret = {
"**": [
"sidebar/brand.html",
"sidebar/search.html",
"sidebar/scroll-start.html",
"sidebar/navigation.html",
"sidebar/ethical-ads.html",
"sidebar/scroll-end.html",
"sidebar/variant-selector.html",
]
}
if not os.path.isfile(
"{}/_templates/sidebar/commercial-support.html".format(root_dir)
):
try:
req = requests.get(url, allow_redirects=True, timeout=10)
except requests.RequestException as e:
print(
"Failed to download the HTML with the eProsima commecial support button."
"Request Error: {}".format(e)
)
return ret
if req.status_code != 200:
print(
"Failed to download the HTML with the eProsima commercial support button."
"Return code: {}".format(req.status_code)
)
return ret
os.makedirs(
os.path.dirname("{}/_templates/sidebar/".format(root_dir)), exist_ok=True
)
html_path = "{}/_templates/sidebar/commercial-support.html".format(root_dir)
with open(html_path, "wb") as f:
try:
f.write(req.content)
except OSError:
print("Failed to create the file: {}".format(html_path))
return ret
if not os.path.isfile("{}/_static/eprosima-logo-white.png".format(root_dir)):
try:
req = requests.get(url_img, allow_redirects=True, timeout=10)
except requests.RequestException as e:
print(
"Failed to download the image for the eProsima commecial support button."
"Request Error: {}".format(e)
)
return ret
if req.status_code != 200:
print(
"Failed to download the image for the eProsima commercial support button."
"Return code: {}".format(req.status_code)
)
return ret
img_path = "{}/_static/eprosima-logo-white.png".format(root_dir)
with open(img_path, "wb") as f:
try:
f.write(req.content)
except OSError:
print("Failed to create the file: {}".format(img_path))
return ret
ret = {
"**": [
"sidebar/brand.html",
"sidebar/commercial-support.html",
"sidebar/search.html",
"sidebar/scroll-start.html",
"sidebar/navigation.html",
"sidebar/ethical-ads.html",
"sidebar/scroll-end.html",
"sidebar/variant-selector.html",
]
}
return ret
def download_file(url, output_path):
"""
Download a file from a URL to a local path.
:param url: The URL of the file to download.
:param output_path: The local path where the file will be saved.
:return: The path to the file if downloaded successfully, the path to a previously downloaded copy of it if the
download fails, or the path to an empty file otherwise. An empty string is returned if no file could be used.
"""
# Normalize path to avoid problems in Windows.
output_path = os.path.normpath(output_path)
try:
req = requests.get(url, allow_redirects=True, timeout=10)
req.raise_for_status() # Raise an error for bad responses
os.makedirs(os.path.dirname(output_path), exist_ok=True)
with open(output_path, "wb") as f:
f.write(req.content)
return output_path
except requests.RequestException as e:
print(f"Failed to download the file from {url}. Request Error: {e}")
except OSError as e:
print(f"Failed to create the file at {output_path}. OS Error: {e}")
# Reuse a previously downloaded copy of the file if there is one. This keeps the build working when the file
# cannot be written, for instance when it was created by a build run as another user.
if os.path.isfile(output_path):
print(f"Using the file already available at {output_path}")
return output_path
# Create an empty file if the download fails
try:
os.makedirs(os.path.dirname(output_path), exist_ok=True)
with open(output_path, "wb") as f:
pass # Create an empty file
print(f"Created an empty file at {output_path}")
return output_path
except OSError as e:
print(f"Failed to create an empty file at {output_path}. OS Error: {e}")
return ""
def static_relative(path):
"""
Get the relative path after "_static" in a posix style.
:param path: The original path.
:return: The relative path after "_static" in a posix style.
"""
if not path:
return ""
parts = path.split(os.path.sep)
if "_static" in parts:
idx = len(parts) - 1 - parts[::-1].index("_static")
rel_parts = parts[idx + 1 :]
return "/".join(rel_parts) if rel_parts else ""
return path
def get_git_branch():
"""Get the git branch this repository is currently on.
On Read the Docs the repo is checked out in detached-HEAD mode, so
``git name-rev`` returns synthetic names like ``remotes/origin/external-1234``
instead of the real branch. A workaround is provided using
``READTHEDOCS_VERSION_TYPE`` and ``READTHEDOCS_VERSION`` according to the build type:
- ``"branch"`` builds: READTHEDOCS_VERSION is the branch name (e.g. ``"3.6.x"``) → use it.
Exception: RTD pseudo-name ``"latest"`` is not a real git branch; return None so
resolve_fallback_branch falls back to master/main.
Exception: RTD pseudo-name ``"stable"`` is not a real git branch either; instead we
query ``git describe --tags --abbrev=0 HEAD`` to get the nearest ancestor tag (e.g.
``"v3.6.1"``), which works whether HEAD is exactly at the tag or has moved past it.
- ``"tag"`` builds: READTHEDOCS_VERSION is the tag name (e.g. ``"v3.6.0"``) → use it.
- ``"external"`` (PR preview) builds: READTHEDOCS_VERSION is the PR number (e.g. ``"1241"``)
which is not a valid git ref. In this case we return None so resolve_fallback_branch falls
back to its default instead of generating broken GitHub URLs.
- Local builds: READTHEDOCS_VERSION_TYPE is unset → fall back to git name-rev.
"""
rtd_type = os.environ.get("READTHEDOCS_VERSION_TYPE")
if rtd_type in ("branch", "tag"):
version_name = os.environ.get("READTHEDOCS_VERSION")
if version_name in ("latest", "stable"):
# "latest" and "stable" are RTD pseudo-names, but RTD also exposes the git ref it actually
# checked out for them (e.g. "3.6.x" or "v3.6.1"). Preferring it keeps the API Reference and the
# GitHub links on the branch the documentation is really being built from instead of master.
# The ref is validated against the remote before being used for the checkout, so an unexpected
# value simply falls back to master as before.
git_identifier = os.environ.get("READTHEDOCS_GIT_IDENTIFIER")
if git_identifier and git_identifier not in ("latest", "stable"):
return git_identifier
if version_name == "latest":
# "latest" is an RTD pseudo-name, not a real branch → fall back to master.
return None
if version_name == "stable":
# "stable" is an RTD pseudo-name. Find the latest vX.Y.Z tag in the repo.
# Release tags live on dedicated branches (not main), so we scan all tags
# rather than restricting to those reachable from HEAD.
path_to_here = os.path.abspath(os.path.dirname(__file__))
try:
p = subprocess.Popen(
["git", "tag", "--sort=-version:refname"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=path_to_here,
)
tags = p.communicate()[0].decode().splitlines()
release_tag_re = re.compile(r'^v\d+\.\d+\.\d+$')
for tag in tags:
if release_tag_re.match(tag.strip()):
return tag.strip()
except Exception:
pass
return None
return version_name
if rtd_type == "external":
return None
path_to_here = os.path.abspath(os.path.dirname(__file__))
# Invoke git to get the current branch which we use to get the theme
try:
p = subprocess.Popen(
["git", "rev-parse", "--verify", "HEAD"],
stdout=subprocess.PIPE,
cwd=path_to_here,
)
commit = p.communicate()[0].decode().rstrip()
p = subprocess.Popen(
["git", "name-rev", "--name-only", commit],
stdout=subprocess.PIPE,
cwd=path_to_here,
)
return p.communicate()[0].decode().rstrip()
except Exception:
# Local build without git or some error occurred
print("Could not get the branch")
# Couldn't figure out the branch probably due to an error
return None
def resolve_fallback_branch(env_var, docs_branch, default="master"):
"""
Resolve the branch to use for GitHub links.
Priority:
1. Environment variable ``env_var`` (e.g. FASTDDS_BRANCH)
2. Current documentation branch (``docs_branch``)
3. Hard-coded ``default``
This mirrors the checkout logic used in the ReadTheDocs clone block so
that extlinks and the actual checkout always point at the same branch.
"""
return os.environ.get(env_var) or docs_branch or default
_NOTES_INCLUDE_RE = re.compile(
r"""\.\.\s+include::\s+(?P<path>previous_versions/v[\d.]+(?:-pro)?\.rst)"""
)
_HEADING_VERSION_RE = re.compile(r"""Version\s+(?P<version>\d+(?:\.\d+){1,3})""")
def parse_latest_version_from_notes(notes_rst_path, fallback):
"""
Read the current latest version number straight out of notes.rst / notes_pro.rst.
Whoever ships a new Fast DDS (or Fast DDS Pro) release already has to add a
new `previous_versions/vX.Y.Z(.W)(-pro).rst` changelog fragment, write its
"Version X.Y.Z" heading, and point notes.rst / notes_pro.rst's
`.. include::` at it. Reading the version back out of that fragment's own
heading means the number shown under the logo always matches what the
docs actually say - no separate value to remember to bump, and no extra
sibling repository checkout required.
"""
try:
with open(notes_rst_path, "r") as f:
content = f.read()
except OSError:
print('Could not read "{}"; falling back to "{}"'.format(notes_rst_path, fallback))
return fallback
include_match = _NOTES_INCLUDE_RE.search(content)
if not include_match:
print('No changelog fragment included in "{}"; falling back to "{}"'.format(notes_rst_path, fallback))
return fallback
fragment_path = os.path.join(os.path.dirname(notes_rst_path), include_match.group("path"))
try:
with open(fragment_path, "r") as f:
fragment_content = f.read()
except OSError:
print('Could not read "{}"; falling back to "{}"'.format(fragment_path, fallback))
return fallback
heading_match = _HEADING_VERSION_RE.search(fragment_content)
if not heading_match:
print('No "Version X.Y.Z" heading found in "{}"; falling back to "{}"'.format(fragment_path, fallback))
return fallback
return heading_match.group("version")
def configure_doxyfile(
doxyfile_in,
doxyfile_out,
input_dir,
output_dir,
project_binary_dir,
project_source_dir,
):
"""
Configure Doxyfile in the CMake style.
:param doxyfile_in: Path to input Doxygen configuration file
:param doxyfile_out: Path to output Doxygen configuration file
:param input_dir: CMakeLists.txt value of DOXYGEN_INPUT_DIR
:param output_dir: CMakeLists.txt value of DOXYGEN_OUTPUT_DIR
:param project_binary_dir: CMakeLists.txt value of PROJECT_BINARY_DIR
:param project_source_dir: CMakeLists.txt value of PROJECT_SOURCE_DIR
"""
print("Configuring Doxyfile")
with open(doxyfile_in, "r") as file:
filedata = file.read()
filedata = filedata.replace("@DOXYGEN_INPUT_DIR@", input_dir)
filedata = filedata.replace("@DOXYGEN_OUTPUT_DIR@", output_dir)
filedata = filedata.replace("@PROJECT_BINARY_DIR@", project_binary_dir)
filedata = filedata.replace("@PROJECT_SOURCE_DIR@", project_source_dir)
os.makedirs(os.path.dirname(doxyfile_out), exist_ok=True)
with open(doxyfile_out, "w") as file:
file.write(filedata)
def resolve_remote_ref(url, preferred_ref, display_name):
"""
Resolve the branch or tag a repository must be checked out at, without downloading it.
``git ls-remote`` is used so that falling back to master, when the remote does not have
``preferred_ref``, does not require cloning anything first.
:param url: URL of the repository.
:param preferred_ref: Branch or tag to use if the remote has it.
:param display_name: Repository name, used for logging.
:return: Tuple with the branch or tag to use and the commit it points to. The commit is ``None`` if the
remote could not be queried.
"""
ref = preferred_ref
try:
remote_refs = git.cmd.Git().ls_remote("--heads", "--tags", url, ref, "master")
except git.GitCommandError as e:
print("Failed to list the refs of {}. Git Error: {}".format(display_name, e))
return ref, None
# ``git ls-remote`` matches the pattern against the tail of the ref path, so asking for "master" also
# matches a branch named "feature/some-work/master". Require an exact branch or tag match, otherwise the
# clone would be attempted with a ref that does not exist and fail instead of falling back.
commits = {}
for line in remote_refs.splitlines():
commit, _, ref_path = line.partition("\t")
commits[ref_path] = commit
for candidate in (ref, "master"):
for ref_path in (
"refs/heads/{}".format(candidate),
"refs/tags/{}".format(candidate),
):
if ref_path in commits:
return candidate, commits[ref_path]
print(
'{} does not have branch or tag "{}"; falling back to master'.format(
display_name, candidate
)
)
return "master", None
def repo_is_at_commit(path, commit, display_name):
"""
Check whether an already cloned repository is checked out at a given commit.
:param path: Local path of the repository.
:param commit: Commit that the repository is expected to be checked out at.
:param display_name: Repository name, used for logging.
:return: True only if the repository exists and its HEAD is that commit.
"""
if not commit or not os.path.isdir(path):
return False
try:
head_commit = git.Repo(path).head.commit.hexsha
except Exception as e:
print("Could not read the HEAD of {}. Error: {}".format(display_name, e))
return False
if head_commit != commit:
print(
"{} is checked out at {} instead of {}".format(
display_name, head_commit[:10], commit[:10]
)
)
return False
return True
def clone_repo_at_ref(url, path, ref, display_name):
"""
Clone a repository at a given branch or tag, downloading as little as possible.
Only the tip of the ref is fetched (``--depth 1``), which is all that doxygen and SWIG need: the full
history of Fast DDS is over 100 MB and none of it is used.
:param url: URL of the repository to clone.
:param path: Local path where the repository will be cloned.
:param ref: Branch or tag to check out, as resolved by ``resolve_remote_ref``.
:param display_name: Repository name, used for logging.
:return: The cloned repository.
"""
print('Cloning {} at "{}"'.format(display_name, ref))
return git.Repo.clone_from(url, path, branch=ref, depth=1, single_branch=True)
script_path = os.path.abspath(pathlib.Path(__file__).parent.absolute())
# Project directories
project_source_dir = os.path.abspath("{}/../code".format(script_path))
project_binary_dir = os.path.abspath("{}/../build".format(script_path))
output_dir = os.path.abspath("{}/doxygen".format(project_binary_dir))
doxygen_html = os.path.abspath("{}/html/doxygen".format(project_binary_dir))
fastdds_python_imported_location = None
# Doxyfile
doxyfile_in = os.path.abspath("{}/doxygen-config.in".format(project_source_dir))
doxyfile_out = os.path.abspath("{}/doxygen-config".format(project_binary_dir))
# Header files
input_dir = os.path.abspath("{}/fastdds/include/fastdds".format(project_binary_dir))
# Current branch of the documentation repository — resolved once, used everywhere.
docs_branch = get_git_branch()
if docs_branch:
print('Current documentation branch is "{}"'.format(docs_branch))
else:
print("Current documentation branch could not be determined; " \
"GitHub links will point to default branches instead of the corresponding branch.")
# Resolve GitHub link branches: env var → current docs branch → default.
# Computed here so they are available both in the ReadTheDocs clone block and in extlinks.
fastdds_fallback_branch = resolve_fallback_branch("FASTDDS_BRANCH", docs_branch, "master")
fastdds_docs_fallback_branch = resolve_fallback_branch("FASTDDS_DOCS_BRANCH", docs_branch, "master")
fastdds_python_fallback_branch = resolve_fallback_branch("FASTDDS_PYTHON_BRANCH", docs_branch, "master")
fastdds_gen_fallback_branch = resolve_fallback_branch("FASTDDS_GEN_BRANCH", docs_branch, "master")
print("Fallback branches for GitHub links:")
print(' Fast-DDS: "{}"'.format(fastdds_fallback_branch))
print(' Fast-DDS-docs: "{}"'.format(fastdds_docs_fallback_branch))
print(' Fast-DDS-Python: "{}"'.format(fastdds_python_fallback_branch))
print(' Fast-DDS-Gen: "{}"'.format(fastdds_gen_fallback_branch))
fastdds_repo_name = os.path.abspath("{}/fastdds".format(project_binary_dir))
fastdds_python_repo_name = os.path.abspath(
"{}/fastdds_python".format(project_binary_dir)
)
# Check if we're running on Read the Docs' servers
read_the_docs_build = os.environ.get("READTHEDOCS", None) == "True"
if read_the_docs_build:
print("Read the Docs environment detected!")
fastdds_url = "https://github.com/eProsima/Fast-DDS.git"
fastdds_python_url = "https://github.com/eProsima/Fast-DDS-python.git"
doxygen_index = os.path.join(output_dir, "xml", "index.xml")
swig_output = os.path.join(
fastdds_python_repo_name, "fastdds_python", "src", "swig", "fastddsPYTHON_wrap.cxx"
)
# Branch or tag, and the commit it currently points to, that each repository must be checked out at
fastdds_ref, fastdds_commit = resolve_remote_ref(
fastdds_url, fastdds_fallback_branch, "Fast DDS"
)
fastdds_python_ref, fastdds_python_commit = resolve_remote_ref(
fastdds_python_url, fastdds_python_fallback_branch, "Fast DDS Python Bindings"
)
# Read the Docs runs a separate sphinx-build, which imports this file again, for every enabled output
# format. Cloning the repositories and running doxygen and SWIG once per format would repeat several
# minutes of work, so the preparation is skipped when a previous run of this build already completed it.
# The repositories must be checked out at the expected commit, and not merely exist, for their doxygen
# documentation and SWIG code to be the ones this build needs.
if (
repo_is_at_commit(fastdds_repo_name, fastdds_commit, "Fast DDS")
and repo_is_at_commit(
fastdds_python_repo_name, fastdds_python_commit, "Fast DDS Python Bindings"
)
and os.path.isfile(doxygen_index)
and os.path.isfile(swig_output)
):
print(
"Reusing the repositories, doxygen documentation and SWIG code already generated in {}".format(
project_binary_dir
)
)
else:
# Remove the repositories left behind by an incomplete attempt, as cloning needs an empty directory
if os.path.isdir(fastdds_repo_name):
print("Removing existing repository in {}".format(fastdds_repo_name))
shutil.rmtree(fastdds_repo_name)
if os.path.isdir(fastdds_python_repo_name):
print("Removing existing repository in {}".format(fastdds_python_repo_name))
shutil.rmtree(fastdds_python_repo_name)
# Create necessary directory path
os.makedirs(os.path.dirname(fastdds_repo_name), exist_ok=True)
os.makedirs(os.path.dirname(fastdds_python_repo_name), exist_ok=True)
# Clone repositories at the branch or tag this documentation is being built from
clone_repo_at_ref(fastdds_url, fastdds_repo_name, fastdds_ref, "Fast DDS")
clone_repo_at_ref(
fastdds_python_url,
fastdds_python_repo_name,
fastdds_python_ref,
"Fast DDS Python Bindings",
)
os.makedirs(os.path.dirname(output_dir), exist_ok=True)
os.makedirs(os.path.dirname(doxygen_html), exist_ok=True)
# Configure Doxyfile
configure_doxyfile(
doxyfile_in,
doxyfile_out,
input_dir,
output_dir,
project_binary_dir,
project_source_dir,
)
# Generate doxygen documentation
doxygen_ret = subprocess.call("doxygen {}".format(doxyfile_out), shell=True)
if doxygen_ret != 0:
print("Doxygen failed with return code {}".format(doxygen_ret))
sys.exit(doxygen_ret)
# Generate SWIG code.
swig_ret = subprocess.call(
"swig \
-python \
-doxygen \
-I{}/include \
-DFASTDDS_DOCS_BUILD \
-outdir {}/fastdds_python/src/swig \
-c++ \
-interface _fastdds_python \
-o {}/fastdds_python/src/swig/fastddsPYTHON_wrap.cxx \
{}/fastdds_python/src/swig/fastdds.i".format(
fastdds_repo_name,
fastdds_python_repo_name,
fastdds_python_repo_name,
fastdds_python_repo_name,
),
shell=True,
)
if swig_ret != 0:
print("SWIG failed with return code {}".format(swig_ret))
sys.exit(swig_ret)
fastdds_python_imported_location = "{}/fastdds_python/src/swig".format(
fastdds_python_repo_name
)
autodoc_mock_imports = ["_fastdds_python"]
# Resolve the Basic and Pro product versions from notes.rst / notes_pro.rst's
# own `.. include::` line - see `parse_latest_version_from_notes` above.
fastdds_version = parse_latest_version_from_notes(
os.path.join(script_path, "notes", "notes.rst"), fallback="3.6.2"
)
fastdds_pro_version = parse_latest_version_from_notes(
os.path.join(script_path, "notes", "notes_pro.rst"), fallback="3.6.2.1"
)
breathe_projects = {"FastDDS": os.path.abspath("{}/xml".format(output_dir))}
breathe_default_project = "FastDDS"
breathe_show_define_initializer = True
# Tell `autodoc` where is the Pydoc documentation if it was set.
if fastdds_python_imported_location:
sys.path.insert(0, fastdds_python_imported_location)
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
"breathe",
"sphinxcontrib.plantuml",
"sphinx_copybutton",
"sphinx_design",
"sphinx.ext.autodoc", # Document Pydoc documentation from Python bindings.
"sphinx.ext.extlinks",
"sphinx_substitution_extensions",
"sphinx_toolbox.collapse",
]
extlinks = {
# Fast-DDS repo (tree = directory, blob = file)
"fastdds-tree": (
f"https://github.com/eProsima/Fast-DDS/tree/{fastdds_fallback_branch}/%s", "%s"
),
"fastdds-blob": (
f"https://github.com/eProsima/Fast-DDS/blob/{fastdds_fallback_branch}/%s", "%s"
),
# Fast-DDS-python repo
"fastdds-python-tree": (
f"https://github.com/eProsima/Fast-DDS-Python/tree/{fastdds_python_fallback_branch}/%s", "%s"
),
# Fast-DDS-docs repo (code examples embedded in the docs repo)
"fastdds-docs-tree": (
f"https://github.com/eProsima/Fast-DDS-docs/tree/{fastdds_docs_fallback_branch}/%s", "%s"
),
# Fast-DDS-Gen raw files
"fastddsgen-raw": (
f"https://raw.githubusercontent.com/eProsima/Fast-DDS-Gen/{fastdds_gen_fallback_branch}/%s",
"%s",
),
}
sphinx_tabs_disable_css_loading = False
sphinx_tabs_disable_tab_closing = True
try:
import sphinxcontrib.spelling # noqa: F401
extensions.append("sphinxcontrib.spelling")
spelling_word_list_filename = [
"spelling_wordlist.txt",
"api_spelling_wordlist.txt",
]
from sphinxcontrib.spelling.filters import ContractionFilter
spelling_filters = [ContractionFilter]
spelling_ignore_contributor_names = False
spelling_verbose = True
except ImportError:
pass
# Default behaviour for `autodoc`: always show documented members.
autodoc_default_options = {
"members": True,
"undoc-members": False,
}
plantuml = "/usr/bin/plantuml -Djava.awt.headless=true "
if sys.platform.startswith("win"):
plantuml = (
"C:\\ProgramData\\chocolatey\\bin\\plantuml.exe -Djava.awt.headless=true "
)
plantuml_output_format = "svg"
# Add any paths that contain templates here, relative to this directory.
templates_path = ["_templates"]
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = ".rst"
# The encoding of source files.
#
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = "index"
# General information about the project.
project = "Fast DDS"
copyright = "2019, eProsima"
author = "eProsima"
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# NOTE: the root CMakeLists.txt does a raw text scan of this exact line
# (`^version = "X.Y.Z"`) to keep the CMake project version in sync with
# Sphinx's, so this must stay a plain quoted literal - it cannot be replaced
# with a computed value. Bump it by hand alongside each Basic release, same
# as before. See `logo_version_html` below for the dynamically-resolved
# Basic/Pro version display under the logo, which is independent of this.
#
# The short X.Y version.
version = "3.6.2"
# The full version, including alpha/beta/rc tags.
release = "3.6.2"
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = "en"
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#
# today = ''
#
# Else, today_fmt is used as the format for a strftime call.
#
# today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = [
"*/includes/*.rst",
"*/*/includes/*.rst",
"*/*/*/includes/*.rst",
"*/*/*/*/includes/*.rst",
"notes/previous_versions/v*.rst",
]
# The reST default role (used for this markup: `text`) to use for all
# documents.
#
# default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#
# add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#
# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#
# show_authors = False
# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
# keep_warnings = False
suppress_warnings = [
"cpp.duplicate_declaration",
"cpp.parse_function_declaration",
"config.cache",
]
# Check if we are checking the spelling. In this case...
if "spelling" in sys.argv or "skip_python=" in sys.argv:
# Exclude Python API Reference because `autodoc` shows warnings.
exclude_patterns.append("fastdds/python_api_reference/dds_pim/*")
# Avoid the warning of a wrong reference in the TOC entries,
# because fails the Python API Reference reference.
suppress_warnings.append("toc.excluded")
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ["_static"]
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = "furo"
html_logo = "_static/fast-dds-logo.png"
# The name for this set of Sphinx documents.
# "<project> v<release> documentation" by default.
# Repurposed here (like Fast-DDS-monitor's docs) to show the latest Basic and
# Pro version numbers under the logo, since furo's stock `sidebar/brand.html`
# renders `html_title` unescaped right below the logo image.
#
logo_version_html = f"<center><i>{fastdds_version} / {fastdds_pro_version} Pro</i></center>"
html_title = logo_version_html
# The name of an image file (relative to this directory) to use as a favicon of
# the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#
html_favicon = "_static/eprosima-logo.svg"
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
html_theme_options = {}
html_theme_options.update(download_json())
html_use_smartypants = True
# The CSS files referenced here should have a path relative to the _static folder.
# We use static_relative(download_file(...)) to ensure the resulting paths are relative to "_static".
# Empty entries are discarded: an unavailable file would otherwise be resolved to the "_static" directory itself,
# making the theme fail to render with "IsADirectoryError".
html_css_files = [
css_file
for css_file in [
static_relative(
download_file(
"https://raw.githubusercontent.com/eProsima/all-docs/master/source/_static/css/eprosima-furo.css",
"{}/_static/css/eprosima-furo.css".format(script_path),
)
),
static_relative(
download_file(
"https://raw.githubusercontent.com/eProsima/all-docs/master/source/_static/css/pro-badge.css",
"{}/_static/css/pro-badge.css".format(script_path),
)
),
]
if css_file
]
# Preserves the left sidebar's scroll position across page navigations.
html_js_files = ["js/sidebar_scroll.js"]
# Custom substitutions that are included at the beginning of every source file.
# |Pro|: badge with PRO text. Place it after titles where needed as follows:
# Title |Pro|
# ===========
# rst_prolog = r"""
# .. |Pro| replace:: :bdg-primary-line:`Pro`
# """
rst_prolog = f"""
.. |Pro| raw:: html
<span class="sd-badge sd-outline-primary sd-text-primary" title="Exclusive to Fast DDS Pro">Pro</span>
.. |ProjectVersion| replace:: {version}
.. |FastDDSBranch| replace:: {fastdds_fallback_branch}
.. |FastDDSPythonBranch| replace:: {fastdds_python_fallback_branch}
"""
# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []
# A shorter title for the navigation bar. Default is the same as html_title.
#
# html_short_title = None
# html_style = 'css/custom.css'
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#
# html_extra_path = []
# If not None, a 'Last updated on:' timestamp is inserted at every page
# bottom, using the given strftime format.
# The empty string is equivalent to '%b %d, %Y'.
#
# html_last_updated_fmt = None
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#
# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#
html_sidebars = retrieve_custom_sidebar(script_path)
# Additional templates that should be rendered to pages, maps page names to
# template names.
#
# html_additional_pages = {}
# If false, no module index is generated.
#
# html_domain_indices = True
# If false, no index is generated.
#
# html_use_index = True