-
Notifications
You must be signed in to change notification settings - Fork 912
Expand file tree
/
Copy pathconf.py
More file actions
408 lines (333 loc) · 14.6 KB
/
Copy pathconf.py
File metadata and controls
408 lines (333 loc) · 14.6 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
# -*- coding: utf-8 -*-
#
# Chipyard documentation build configuration file, created by
# sphinx-quickstart on Fri Mar 8 11:46:38 2019.
#
# 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 os
# import sys
# sys.path.insert(0, os.path.abspath('.'))
from datetime import datetime
import os
import subprocess
import sys
# -- 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 = [
'sphinx.ext.autodoc',
'sphinx.ext.intersphinx',
'sphinx.ext.todo',
'sphinx.ext.mathjax',
'sphinx.ext.ifconfig',
'sphinx.ext.viewcode',
'sphinx.ext.githubpages',
'sphinx.ext.autosectionlabel',
'sphinx.ext.extlinks',
]
# 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 master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Chipyard'
copyright = f'{datetime.now().year}, Berkeley Architecture Research'
author = u'Berkeley Architecture Research'
# 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.
on_rtd = os.environ.get("READTHEDOCS") == "True"
on_gha = os.environ.get("GITHUB_ACTIONS") == "true"
if on_rtd:
for item, value in os.environ.items():
print("[READTHEDOCS] {} = {}".format(item, value))
def get_git_tag():
# get the latest git tag (which is what rtd normally builds under "stable")
# this works since rtd builds things within the repo
process = subprocess.Popen(["git", "describe", "--exact-match", "--tags"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
tag = process.communicate()[0].decode("utf-8").strip()
if process.returncode == 0:
return tag
else:
return None
def get_rtd_git_identifier():
# RTD exposes the real branch or tag behind aliases like "stable". This is
# more reliable than git describe when RTD uses a shallow checkout.
identifier = os.environ.get("READTHEDOCS_GIT_IDENTIFIER")
return identifier or None
def get_git_branch_name():
# When running locally, try to set version to a branch name that could be
# used to reference files on GH that could be added or moved. This should match rtd_version when running
# in a RTD build container
process = subprocess.Popen(["git", "rev-parse", "--abbrev-ref", "HEAD"], stdout=subprocess.PIPE)
branchname = process.communicate()[0].decode("utf-8").strip()
if process.returncode == 0:
return branchname
else:
return None
def get_git_remote_url():
"""Get the remote URL of the git repository.
Returns:
str: The HTTPS GitHub URL of the repository, or None if not found/not a GitHub repo.
"""
try:
# Try to get the 'origin' remote URL first
process = subprocess.Popen(["git", "config", "--get", "remote.origin.url"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
url = process.communicate()[0].decode("utf-8").strip()
# If origin doesn't exist, try to get any remote
if process.returncode != 0 or not url:
process = subprocess.Popen(["git", "remote", "-v"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
remotes = process.communicate()[0].decode("utf-8").strip()
if remotes:
# Take the first remote found
first_remote = remotes.split('\n')[0]
remote_name = first_remote.split()[0]
process = subprocess.Popen(["git", "config", "--get", f"remote.{remote_name}.url"], stdout=subprocess.PIPE)
url = process.communicate()[0].decode("utf-8").strip()
# Convert SSH URL to HTTPS URL if necessary
if url.startswith("git@github.com:"):
# Transform git@github.com:username/repo.git to https://github.com/username/repo
url = "https://github.com/" + url[15:]
# Remove .git suffix if present
if url.endswith(".git"):
url = url[:-4]
# Handle other GitHub URL formats
if "github.com" in url:
# Extract username/repo part for any GitHub URL format
if "https://github.com/" in url:
repo_path = url.split("https://github.com/")[1]
elif "http://github.com/" in url:
repo_path = url.split("http://github.com/")[1]
else:
# For other GitHub URL formats
return None
# Handle potential trailing slashes
repo_path = repo_path.strip("/")
return f"https://github.com/{repo_path}"
return None
except Exception as e:
print(f"Error getting git remote URL: {e}")
return None
# Come up with a short version string for the build. This is doing a bunch of lifting:
# - format doc text that self-references its version (see title page). This may be used in an ad-hoc
# way to produce references to things like ScalaDoc, etc...
# - procedurally generate github URL references using via `gh-file-ref`
#
# For Chipyard, the RTD version can be multiple things:
# 1. 'stable' - This points to a branch called 'stable' in the repo. that was previously manually updated each release. This is outdated.
# 2. 'latest' - This points to the 'main' branch documentation. This is recommended.
# 3. '<another-branch-name>' - This points to a branch. Normally used for testing if a branches documentation builds.
if on_rtd:
rtd_version = os.environ.get("READTHEDOCS_VERSION")
if rtd_version == "latest":
branchname = get_git_branch_name() or get_rtd_git_identifier()
assert branchname is not None
version = branchname
elif rtd_version == "stable":
tag = get_git_tag() or get_rtd_git_identifier()
assert tag is not None
version = tag
else:
version = rtd_version # should be name of a branch
elif on_gha:
rtd_version = "latest"
# GitHub actions does a build of the docs to ensure they are free of warnings.
# Looking up a branch name or tag requires switching on the event type that triggered the workflow
# so just use the SHA of the commit instead.
version = os.environ.get("GITHUB_SHA")
else:
rtd_version = "latest"
# When running locally, try to set version to a branch name that could be
# used to reference files on GH that could be added or moved. This should match rtd_version when running
# in a RTD build container
branchname = get_git_branch_name()
assert branchname is not None
version = branchname
# for now make these match
release = version
# 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"
# 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 = ['_build', 'Thumbs.db', '.DS_Store']
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_rtd_theme'
# 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 = {
'collapse_navigation': False,
'logo_only': True,
# 'display_version': True,
# 'navigation_depth': 4,
}
# 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']
html_css_files = [
'css/custom.css',
]
# Custom sidebar templates, must be a dictionary that maps document names
# to template names.
#
# This is required for the alabaster theme
# refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars
html_sidebars = {
'**': [
'about.html',
'navigation.html',
'relations.html', # needs 'show_related': True theme option to display
'searchbox.html',
'donate.html',
]
}
html_logo = '_static/images/chipyard-logo.png'
# -- Options for HTMLHelp output ------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'Chipyarddoc'
# -- Misc Options ---------------------------------------------------------
html_context = {
"version": version
}
# add rst to end of each rst source file
# can put custom strings here that are generated from this file
rst_epilog = f"""
.. |overall_version| replace:: {version}
"""
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'Chipyard.tex', u'Chipyard Documentation',
u'Berkeley Architecture Research', 'manual'),
]
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'chipyard', u'Chipyard Documentation',
[author], 1)
]
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'Chipyard', u'Chipyard Documentation',
author, 'Chipyard', 'One line description of project.',
'Miscellaneous'),
]
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'python' : ('https://docs.python.org/', None),
'boom' : ('https://docs.boom-core.org/en/latest/', None),
'firesim' : ('http://docs.fires.im/en/latest/', None) }
# resolve label conflict between documents
autosectionlabel_prefix_document = True
# shorten FireSim references
extlinks = {
'fsim_doc' : ('https://docs.fires.im/en/' + rtd_version + '/%s', 'fsim_doc %s')
}
# -- handle re-directs for pages that move
# taken from https://tech.signavio.com/2017/managing-sphinx-redirects
redirect_files = [ ]
def copy_legacy_redirects(app, docname): # Sphinx expects two arguments
if app.builder.name == 'html':
for html_src_path in redirect_files:
target_path = app.outdir + '/' + html_src_path
src_path = app.srcdir + '/' + html_src_path
if os.path.isfile(src_path):
shutil.copyfile(src_path, target_path)
def gh_file_ref_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
"""
Produces a github.com reference to a blob or tree at path {text}.
Example:
:gh-file-ref:`my/path`
Produces a hyperlink with the text "my/path" that refers the url:
https://www.github.com/repo-owner/repo/blob/<version>/my/path.
Where version is the same as would be substituted by using |version| in
html text, and is resolved in conf.py.
"""
import docutils
import requests
# Get the repository URL dynamically
repo_url = get_git_remote_url()
# Default fallback for safety
if not repo_url:
repo_url = "https://github.com/ucb-bar/chipyard"
print(f"Warning: Could not determine repository URL, using default: {repo_url}")
url = f"{repo_url}/blob/{version}/{text}"
# SKIP_URL_CHECK=1 bypasses the external URL verification entirely so local
# and offline docs builds (e.g. the Starlight sync) don't depend on network
# access to github.com. CI leaves it unset to keep validating for dead links.
if os.environ.get("SKIP_URL_CHECK") != "1":
print(f"Testing GitHub URL {url} exists...")
try:
status_code = requests.get(url).status_code
if status_code != 200:
message = f"[Line {lineno}] :{name}:`{text}` produces URL {url} returning status code {status_code}. " \
"Ensure your path is correct and all commits that may have moved or renamed files have been pushed to github.com."
print(message)
sys.exit(1) # Exit with error in all environments to catch dead links
except requests.exceptions.ConnectionError as e:
print(f"Warning: Network error when verifying URL {url}: {e}")
print("If you're working offline, you can set the SKIP_URL_CHECK=1 environment variable to bypass URL checks.")
sys.exit(1)
except Exception as e:
print(f"Warning: Failed to verify URL {url}: {e}")
sys.exit(1)
docutils.parsers.rst.roles.set_classes(options)
node = docutils.nodes.reference(rawtext, text, refuri=url, **options)
return [node], []
def setup(app):
# Add roles to simplify github reference generation
app.add_role('gh-file-ref', gh_file_ref_role)
app.connect('build-finished', copy_legacy_redirects)