요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.
1. 요약·해설
원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.
2. 영어 원문 전체
번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.
원문 전체 펼치기
# SPDX-License-Identifier: GPL-2.0-only
# pylint: disable=C0103,C0209
"""
The Linux Kernel documentation build configuration file.
"""
import os
import shutil
import sys
from textwrap import dedent
import sphinx
# 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.
sys.path.insert(0, os.path.abspath("sphinx"))
from load_config import loadConfig # pylint: disable=C0413,E0401
# Minimal supported version
needs_sphinx = "3.4.3"
# Get Sphinx version
major, minor, patch = sphinx.version_info[:3] # pylint: disable=I1101
# Include_patterns were added on Sphinx 5.1
if (major < 5) or (major == 5 and minor < 1):
has_include_patterns = False
else:
has_include_patterns = True
# Include patterns that don't contain directory names, in glob format
include_patterns = ["**.rst"]
# Location of Documentation/ directory
doctree = os.path.abspath(".")
# Exclude of patterns that don't contain directory names, in glob format.
exclude_patterns = []
# List of patterns that contain directory names in glob format.
dyn_include_patterns = []
dyn_exclude_patterns = ["output"]
# Currently, only netlink/specs has a parser for yaml.
# Prefer using include patterns if available, as it is faster
if has_include_patterns:
dyn_include_patterns.append("netlink/specs/*.yaml")
else:
dyn_exclude_patterns.append("netlink/*.yaml")
dyn_exclude_patterns.append("devicetree/bindings/**.yaml")
dyn_exclude_patterns.append("core-api/kho/bindings/**.yaml")
# Properly handle directory patterns and LaTeX docs
# -------------------------------------------------
def config_init(app, config):
"""
Initialize path-dependent variabled
On Sphinx, all directories are relative to what it is passed as
SOURCEDIR parameter for sphinx-build. Due to that, all patterns
that have directory names on it need to be dynamically set, after
converting them to a relative patch.
As Sphinx doesn't include any patterns outside SOURCEDIR, we should
exclude relative patterns that start with "../".
"""
# setup include_patterns dynamically
if has_include_patterns:
for p in dyn_include_patterns:
full = os.path.join(doctree, p)
rel_path = os.path.relpath(full, start=app.srcdir)
if rel_path.startswith("../"):
continue
config.include_patterns.append(rel_path)
# setup exclude_patterns dynamically
for p in dyn_exclude_patterns:
full = os.path.join(doctree, p)
rel_path = os.path.relpath(full, start=app.srcdir)
if rel_path.startswith("../"):
continue
config.exclude_patterns.append(rel_path)
# LaTeX and PDF output require a list of documents with are dependent
# of the app.srcdir. Add them here
# When SPHINXDIRS is used, we just need to get index.rst, if it exists
if not os.path.samefile(doctree, app.srcdir):
doc = os.path.basename(app.srcdir)
fname = "index"
if os.path.exists(os.path.join(app.srcdir, fname + ".rst")):
latex_documents.append((fname, doc + ".tex",
"Linux %s Documentation" % doc.capitalize(),
"The kernel development community",
"manual"))
return
# When building all docs, or when a main index.rst doesn't exist, seek
# for it on subdirectories
for doc in os.listdir(app.srcdir):
fname = os.path.join(doc, "index")
if not os.path.exists(os.path.join(app.srcdir, fname + ".rst")):
continue
has = False
for l in latex_documents:
if l[0] == fname:
has = True
break
if not has:
latex_documents.append((fname, doc + ".tex",
"Linux %s Documentation" % doc.capitalize(),
"The kernel development community",
"manual"))
# helper
# ------
def have_command(cmd):
"""Search ``cmd`` in the ``PATH`` environment.
If found, return True.
If not found, return False.
"""
return shutil.which(cmd) is not None
# -- General configuration ------------------------------------------------
# Add any Sphinx extensions in alphabetic order
extensions = [
"automarkup",
"kernel_abi",
"kerneldoc",
"kernel_feat",
"kernel_include",
"kfigure",
"maintainers_include",
"parser_yaml",
"rstFlatTable",
"sphinx.ext.autosectionlabel",
"sphinx.ext.ifconfig",
"translations",
]
# Since Sphinx version 3, the C function parser is more pedantic with regards
# to type checking. Due to that, having macros at c:function cause problems.
# Those needed to be escaped by using c_id_attributes[] array
c_id_attributes = [
# GCC Compiler types not parsed by Sphinx:
"__restrict__",
# include/linux/compiler_types.h:
"__iomem",
"__kernel",
"noinstr",
"notrace",
"__percpu",
"__rcu",
"__user",
"__force",
"__counted_by_le",
"__counted_by_be",
# include/linux/compiler_attributes.h:
"__alias",
"__aligned",
"__aligned_largest",
"__always_inline",
"__assume_aligned",
"__cold",
"__attribute_const__",
"__copy",
"__pure",
"__designated_init",
"__visible",
"__printf",
"__scanf",
"__gnu_inline",
"__malloc",
"__mode",
"__no_caller_saved_registers",
"__noclone",
"__nonstring",
"__noreturn",
"__packed",
"__pure",
"__section",
"__always_unused",
"__maybe_unused",
"__used",
"__weak",
"noinline",
"__fix_address",
"__counted_by",
# include/linux/memblock.h:
"__init_memblock",
"__meminit",
# include/linux/init.h:
"__init",
"__ref",
# include/linux/linkage.h:
"asmlinkage",
# include/linux/btf.h
"__bpf_kfunc",
]
# Ensure that autosectionlabel will produce unique names
autosectionlabel_prefix_document = True
autosectionlabel_maxdepth = 2
# Load math renderer:
# For html builder, load imgmath only when its dependencies are met.
# mathjax is the default math renderer since Sphinx 1.8.
have_latex = have_command("latex")
have_dvipng = have_command("dvipng")
load_imgmath = have_latex and have_dvipng
# Respect SPHINX_IMGMATH (for html docs only)
if "SPHINX_IMGMATH" in os.environ:
env_sphinx_imgmath = os.environ["SPHINX_IMGMATH"]
if "yes" in env_sphinx_imgmath:
load_imgmath = True
elif "no" in env_sphinx_imgmath:
load_imgmath = False
else:
sys.stderr.write("Unknown env SPHINX_IMGMATH=%s ignored.\n" % env_sphinx_imgmath)
if load_imgmath:
extensions.append("sphinx.ext.imgmath")
math_renderer = "imgmath"
else:
math_renderer = "mathjax"
# Add any paths that contain templates here, relative to this directory.
templates_path = ["sphinx/templates"]
# The suffixes of source filenames that will be automatically parsed
source_suffix = {
".rst": "restructuredtext",
".yaml": "yaml",
}
# The encoding of source files.
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = "index"
# General information about the project.
project = "The Linux Kernel"
copyright = "The kernel development community" # pylint: disable=W0622
author = "The kernel development community"
# 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.
#
# In a normal build, version and release are set to KERNELVERSION and
# KERNELRELEASE, respectively, from the Makefile via Sphinx command line
# arguments.
#
# The following code tries to extract the information by reading the Makefile,
# when Sphinx is run directly (e.g. by Read the Docs).
try:
makefile_version = None
makefile_patchlevel = None
with open("../Makefile", encoding="utf=8") as fp:
for line in fp:
key, val = [x.strip() for x in line.split("=", 2)]
if key == "VERSION":
makefile_version = val
elif key == "PATCHLEVEL":
makefile_patchlevel = val
if makefile_version and makefile_patchlevel:
break
except Exception:
pass
finally:
if makefile_version and makefile_patchlevel:
version = release = makefile_version + "." + makefile_patchlevel
else:
version = release = "unknown version"
def get_cline_version():
"""
HACK: There seems to be no easy way for us to get at the version and
release information passed in from the makefile...so go pawing through the
command-line options and find it for ourselves.
"""
c_version = c_release = ""
for arg in sys.argv:
if arg.startswith("version="):
c_version = arg[8:]
elif arg.startswith("release="):
c_release = arg[8:]
if c_version:
if c_release:
return c_version + "-" + c_release
return c_version
return version # Whatever we came up with before
# 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'
# 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
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = "sphinx"
# 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
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
primary_domain = "c"
highlight_language = "none"
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
# Default theme
html_theme = "alabaster"
html_css_files = []
if "DOCS_THEME" in os.environ:
html_theme = os.environ["DOCS_THEME"]
if html_theme in ["sphinx_rtd_theme", "sphinx_rtd_dark_mode"]:
# Read the Docs theme
try:
import sphinx_rtd_theme
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
# 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_css_files = [
"theme_overrides.css",
]
# Read the Docs dark mode override theme
if html_theme == "sphinx_rtd_dark_mode":
try:
import sphinx_rtd_dark_mode # pylint: disable=W0611
extensions.append("sphinx_rtd_dark_mode")
except ImportError:
html_theme = "sphinx_rtd_theme"
if html_theme == "sphinx_rtd_theme":
# Add color-specific RTD normal mode
html_css_files.append("theme_rtd_colors.css")
html_theme_options = {
"navigation_depth": -1,
}
except ImportError:
html_theme = "alabaster"
if "DOCS_CSS" in os.environ:
css = os.environ["DOCS_CSS"].split(" ")
for l in css:
html_css_files.append(l)
if html_theme == "alabaster":
html_theme_options = {
"description": get_cline_version(),
"page_width": "65em",
"sidebar_width": "15em",
"fixed_sidebar": "true",
"font_size": "inherit",
"font_family": "serif",
}
sys.stderr.write("Using %s theme\n" % html_theme)
# 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 = ["sphinx-static"]
# If true, Docutils "smart quotes" will be used to convert quotes and dashes
# to typographically correct entities. However, conversion of "--" to "—"
# is not always what we want, so enable only quotes.
smartquotes_action = "q"
# Custom sidebar templates, maps document names to template names.
# Note that the RTD theme ignores this
html_sidebars = {"**": ["searchbox.html",
"kernel-toc.html",
"sourcelink.html"]}
# about.html is available for alabaster theme. Add it at the front.
if html_theme == "alabaster":
html_sidebars["**"].insert(0, "about.html")
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
html_logo = "images/logo.svg"
# Output file base name for HTML help builder.
htmlhelp_basename = "TheLinuxKerneldoc"
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
"papersize": "a4paper",
"passoptionstopackages": dedent(r"""
\PassOptionsToPackage{svgnames}{xcolor}
"""),
# The font size ('10pt', '11pt' or '12pt').
"pointsize": "11pt",
# Needed to generate a .ind file
"printindex": r"\footnotesize\raggedright\printindex",
# Latex figure (float) alignment
# 'figure_align': 'htbp',
# Don't mangle with UTF-8 chars
"fontenc": "",
"inputenc": "",
"utf8extra": "",
# Set document margins
"sphinxsetup": dedent(r"""
hmargin=0.5in, vmargin=1in,
parsedliteralwraps=true,
verbatimhintsturnover=false,
"""),
#
# Some of our authors are fond of deep nesting; tell latex to
# cope.
#
"maxlistdepth": "10",
# For CJK One-half spacing, need to be in front of hyperref
"extrapackages": r"\usepackage{setspace}",
"fontpkg": dedent(r"""
\usepackage{fontspec}
\setmainfont{DejaVu Serif}
\setsansfont{DejaVu Sans}
\setmonofont{DejaVu Sans Mono}
\newfontfamily\headingfont{DejaVu Serif}
"""),
"preamble": dedent(r"""
% Load kerneldoc specific LaTeX settings
\input{kerneldoc-preamble.sty}
""")
}
# This will be filled up by config-inited event
latex_documents = []
# The name of an image file (relative to this directory) to place at the top of
# the title page.
# latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
# latex_use_parts = False
# If true, show page references after internal links.
# latex_show_pagerefs = False
# If true, show URL addresses after external links.
# latex_show_urls = False
# Documents to append as an appendix to all manuals.
# latex_appendices = []
# If false, no module index is generated.
# latex_domain_indices = True
# Additional LaTeX stuff to be copied to build directory
latex_additional_files = [
"sphinx/kerneldoc-preamble.sty",
]
# -- 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, "thelinuxkernel", "The Linux Kernel Documentation", [author], 1)
]
# If true, show URL addresses after external links.
# man_show_urls = False
# -- 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,
"TheLinuxKernel",
"The Linux Kernel Documentation",
author,
"TheLinuxKernel",
"One line description of project.",
"Miscellaneous",
),]
# -- Options for Epub output ----------------------------------------------
# Bibliographic Dublin Core info.
epub_title = project
epub_author = author
epub_publisher = author
epub_copyright = copyright
# A list of files that should not be packed into the epub file.
epub_exclude_files = ["search.html"]
# =======
# rst2pdf
#
# Grouping the document tree into PDF files. List of tuples
# (source start file, target name, title, author, options).
#
# See the Sphinx chapter of https://ralsina.me/static/manual.pdf
#
# FIXME: Do not add the index file here; the result will be too big. Adding
# multiple PDF files here actually tries to get the cross-referencing right
# *between* PDF files.
pdf_documents = [
("kernel-documentation", "Kernel", "Kernel", "J. Random Bozo"),
]
# kernel-doc extension configuration for running Sphinx directly (e.g. by Read
# the Docs). In a normal build, these are supplied from the Makefile via command
# line arguments.
kerneldoc_bin = "../scripts/kernel-doc.py"
kerneldoc_srctree = ".."
# ------------------------------------------------------------------------------
# Since loadConfig overwrites settings from the global namespace, it has to be
# the last statement in the conf.py file
# ------------------------------------------------------------------------------
loadConfig(globals())
def setup(app):
"""Patterns need to be updated at init time on older Sphinx versions"""
app.connect('config-inited', config_init)
3. 한국어 전문 번역
영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.
부트스트랩, 동적 경로 패턴과 LaTeX 문서 목록
1-138이 파일은 Linux 커널 `Documentation/` 트리를 Sphinx로 빌드하는 중앙 Python 설정입니다. GPL-2.0-only 라이선스와 pylint 예외를 선언한 뒤 표준 모듈, Sphinx, 커널 전용 `load_config`를 불러오며, `Documentation/sphinx`를 모듈 검색 경로 맨 앞에 추가합니다.
최소 지원 Sphinx 버전은 `3.4.3`입니다. Sphinx `5.1`부터 제공되는 `include_patterns` 지원 여부를 `sphinx.version_info`로 판단하고, 지원하는 경우 기본 RST 패턴 `**.rst`와 netlink YAML만 포함합니다. 이전 버전에서는 YAML 디렉터리를 동적 제외 목록으로 넣어 같은 결과를 우회합니다.
`config_init(app, config)`는 Sphinx의 `config-inited` 시점에 실제 `app.srcdir`을 알게 된 뒤 경로 의존 설정을 계산합니다. `doctree` 기준 패턴을 소스 디렉터리 상대 경로로 바꾸고 `../`로 시작해 현재 빌드 범위 밖에 있는 패턴은 건너뜁니다. 이어서 부분 문서 빌드와 전체 문서 빌드를 구분해 `latex_documents`를 채웁니다.
SOURCEDIR이 정해진 뒤 포함·제외 경로와 PDF용 문서 튜플을 실제 빌드 위치에 맞춥니다.
원문 1-38줄의 모듈과 전역 기준값입니다.
원문 40-55줄은 Sphinx 버전에 따라 YAML 처리 방식을 바꿉니다.
원문 59-124줄 함수의 두 책임을 순서대로 설명합니다.
원문 126-136줄의 작은 의존성 검사 도우미입니다.
Sphinx 확장, C 식별자 속성, 수학 렌더러와 소스 형식
139-262일반 설정은 커널 문서용 확장 12개를 알파벳 순서로 등록합니다. Sphinx 3 이후 엄격해진 C 함수 파서가 커널 매크로를 형식 오류로 판단하지 않도록 `c_id_attributes`에 컴파일러·주소 공간·초기화·BTF 속성 47개를 허용합니다.
수학 렌더러는 `latex`와 `dvipng`가 모두 PATH에 있으면 HTML에서 `sphinx.ext.imgmath`를 추가하고 `imgmath`를 선택합니다. `SPHINX_IMGMATH` 환경 변수에 `yes`가 포함되면 강제로 활성화하고 `no`가 포함되면 비활성화하며, 다른 값은 표준 오류 경고 후 무시합니다. 조건이 충족되지 않으면 기본 `mathjax`를 사용합니다.
도구 가용성을 기본값으로 삼고 SPHINX_IMGMATH가 있으면 이를 우선 적용합니다.
원문 141-155줄의 확장과 기능 범주입니다.
원문 156-220줄의 심볼을 원래 헤더 묶음별로 보존합니다. `__pure`는 원문 목록에 두 번 나타납니다.
원문 222-262줄의 나머지 일반 설정입니다.
프로젝트 메타데이터, 커널 버전과 일반 문서 옵션
264-361프로젝트 이름은 `The Linux Kernel`, 저자와 저작권 표시는 `The kernel development community`입니다. 일반 Makefile 기반 빌드에서는 명령행으로 `KERNELVERSION`과 `KERNELRELEASE`가 들어오지만, Sphinx를 직접 실행하는 환경을 위해 상위 `../Makefile`의 `VERSION`과 `PATCHLEVEL`도 읽습니다.
Makefile을 읽지 못하거나 두 값이 완성되지 않으면 `version`과 `release`를 `unknown version`으로 둡니다. `get_cline_version()`은 `sys.argv`에서 `version=`과 `release=`를 다시 찾아 둘 다 있으면 하이픈으로 결합하고, version만 있으면 그것만, 없으면 앞서 계산한 `version`을 반환합니다.
직접 실행용 Makefile 추출값을 마련한 뒤 명령행 값이 있으면 HTML 설명에 우선 사용합니다.
원문 269-317줄의 예외 처리와 명령행 보완입니다.
원문 320-361줄에서 실제 활성화된 값과 주석 예시를 구분합니다.
HTML 테마, CSS, 사이드바와 정적 자원
363-452HTML 기본 테마는 `alabaster`이며 `DOCS_THEME` 환경 변수로 바꿀 수 있습니다. `sphinx_rtd_theme` 또는 `sphinx_rtd_dark_mode`를 요청하면 관련 모듈을 가져와 테마 경로와 CSS를 설정하고, import가 실패하면 `alabaster`로 되돌아갑니다.
`DOCS_CSS`는 공백으로 나눈 각 파일명을 `html_css_files`에 추가합니다. 최종 테마가 alabaster이면 커널 버전 설명, 페이지·사이드바 폭, 고정 사이드바, 글꼴 설정을 적용합니다. 선택된 테마는 표준 오류에 `Using ... theme`으로 기록됩니다.
환경 변수와 Python 모듈 가용성에 따라 RTD 계열 또는 alabaster 설정으로 수렴합니다.
원문 372-407줄의 import와 폴백 규칙입니다.
원문 409-425줄의 최종 CSS 및 테마 옵션입니다.
원문 427-452줄의 HTML 공통 출력 설정입니다.
LaTeX, man, Texinfo, EPUB, PDF와 최종 설정 연결
454-596LaTeX 출력은 A4, 11pt, 좁은 수평 여백과 1인치 수직 여백, 최대 목록 깊이 10을 사용합니다. UTF-8 문자를 재인코딩하지 않도록 `fontenc`, `inputenc`, `utf8extra`를 비우고, `fontspec`으로 DejaVu Serif·Sans·Sans Mono를 지정하며 `kerneldoc-preamble.sty`를 불러옵니다.
`latex_documents`는 빈 목록으로 시작해 앞의 `config_init()`이 빌드 위치에 따라 채웁니다. man, Texinfo, EPUB, rst2pdf용 메타데이터도 각각 선언하며, Sphinx 직접 실행을 위해 `kerneldoc_bin=../scripts/kernel-doc.py`, `kerneldoc_srctree=..`를 기본값으로 제공합니다.
마지막 전역 호출 `loadConfig(globals())`는 명령행 또는 외부 설정으로 현재 전역값을 덮어써야 하므로 설정 선언 뒤에 놓입니다. `setup(app)`은 Sphinx `config-inited` 이벤트에 `config_init`을 연결해 구버전 Sphinx에서도 동적 패턴을 초기화합니다.
정적 기본값을 만든 뒤 외부 재정의를 적용하고 Sphinx 초기화 이벤트에서 경로 의존 값을 완성합니다.
원문 456-496줄의 인쇄·글꼴·레이아웃 설정입니다.
원문 498-524줄의 동적 목록과 주석 옵션입니다.
원문 527-584줄의 각 출력 형식과 튜플입니다.
출력 백엔드와 설정 후크의 원문 범위입니다.
Linux v6.18.37 conf.py 원문 전체 보존
1-596596줄 파일의 상위 구성을 한눈에 확인하는 색인입니다.
아래 코드는 Linux v6.18.37 원문 1-596줄 전체입니다. 표시 안정성을 위해 탭만 여덟 칸으로 정규화했으며 Python 식별자, 문자열, 경로, 주석, docstring, LaTeX 원시 문자열, 환경 변수, 함수와 설정 순서는 변경하지 않았습니다.
# SPDX-License-Identifier: GPL-2.0-only
# pylint: disable=C0103,C0209
"""
The Linux Kernel documentation build configuration file.
"""
import os
import shutil
import sys
from textwrap import dedent
import sphinx
# 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.
sys.path.insert(0, os.path.abspath("sphinx"))
from load_config import loadConfig # pylint: disable=C0413,E0401
# Minimal supported version
needs_sphinx = "3.4.3"
# Get Sphinx version
major, minor, patch = sphinx.version_info[:3] # pylint: disable=I1101
# Include_patterns were added on Sphinx 5.1
if (major < 5) or (major == 5 and minor < 1):
has_include_patterns = False
else:
has_include_patterns = True
# Include patterns that don't contain directory names, in glob format
include_patterns = ["**.rst"]
# Location of Documentation/ directory
doctree = os.path.abspath(".")
# Exclude of patterns that don't contain directory names, in glob format.
exclude_patterns = []
# List of patterns that contain directory names in glob format.
dyn_include_patterns = []
dyn_exclude_patterns = ["output"]
# Currently, only netlink/specs has a parser for yaml.
# Prefer using include patterns if available, as it is faster
if has_include_patterns:
dyn_include_patterns.append("netlink/specs/*.yaml")
else:
dyn_exclude_patterns.append("netlink/*.yaml")
dyn_exclude_patterns.append("devicetree/bindings/**.yaml")
dyn_exclude_patterns.append("core-api/kho/bindings/**.yaml")
# Properly handle directory patterns and LaTeX docs
# -------------------------------------------------
def config_init(app, config):
"""
Initialize path-dependent variabled
On Sphinx, all directories are relative to what it is passed as
SOURCEDIR parameter for sphinx-build. Due to that, all patterns
that have directory names on it need to be dynamically set, after
converting them to a relative patch.
As Sphinx doesn't include any patterns outside SOURCEDIR, we should
exclude relative patterns that start with "../".
"""
# setup include_patterns dynamically
if has_include_patterns:
for p in dyn_include_patterns:
full = os.path.join(doctree, p)
rel_path = os.path.relpath(full, start=app.srcdir)
if rel_path.startswith("../"):
continue
config.include_patterns.append(rel_path)
# setup exclude_patterns dynamically
for p in dyn_exclude_patterns:
full = os.path.join(doctree, p)
rel_path = os.path.relpath(full, start=app.srcdir)
if rel_path.startswith("../"):
continue
config.exclude_patterns.append(rel_path)
# LaTeX and PDF output require a list of documents with are dependent
# of the app.srcdir. Add them here
# When SPHINXDIRS is used, we just need to get index.rst, if it exists
if not os.path.samefile(doctree, app.srcdir):
doc = os.path.basename(app.srcdir)
fname = "index"
if os.path.exists(os.path.join(app.srcdir, fname + ".rst")):
latex_documents.append((fname, doc + ".tex",
"Linux %s Documentation" % doc.capitalize(),
"The kernel development community",
"manual"))
return
# When building all docs, or when a main index.rst doesn't exist, seek
# for it on subdirectories
for doc in os.listdir(app.srcdir):
fname = os.path.join(doc, "index")
if not os.path.exists(os.path.join(app.srcdir, fname + ".rst")):
continue
has = False
for l in latex_documents:
if l[0] == fname:
has = True
break
if not has:
latex_documents.append((fname, doc + ".tex",
"Linux %s Documentation" % doc.capitalize(),
"The kernel development community",
"manual"))
# helper
# ------
def have_command(cmd):
"""Search ``cmd`` in the ``PATH`` environment.
If found, return True.
If not found, return False.
"""
return shutil.which(cmd) is not None
# -- General configuration ------------------------------------------------
# Add any Sphinx extensions in alphabetic order
extensions = [
"automarkup",
"kernel_abi",
"kerneldoc",
"kernel_feat",
"kernel_include",
"kfigure",
"maintainers_include",
"parser_yaml",
"rstFlatTable",
"sphinx.ext.autosectionlabel",
"sphinx.ext.ifconfig",
"translations",
]
# Since Sphinx version 3, the C function parser is more pedantic with regards
# to type checking. Due to that, having macros at c:function cause problems.
# Those needed to be escaped by using c_id_attributes[] array
c_id_attributes = [
# GCC Compiler types not parsed by Sphinx:
"__restrict__",
# include/linux/compiler_types.h:
"__iomem",
"__kernel",
"noinstr",
"notrace",
"__percpu",
"__rcu",
"__user",
"__force",
"__counted_by_le",
"__counted_by_be",
# include/linux/compiler_attributes.h:
"__alias",
"__aligned",
"__aligned_largest",
"__always_inline",
"__assume_aligned",
"__cold",
"__attribute_const__",
"__copy",
"__pure",
"__designated_init",
"__visible",
"__printf",
"__scanf",
"__gnu_inline",
"__malloc",
"__mode",
"__no_caller_saved_registers",
"__noclone",
"__nonstring",
"__noreturn",
"__packed",
"__pure",
"__section",
"__always_unused",
"__maybe_unused",
"__used",
"__weak",
"noinline",
"__fix_address",
"__counted_by",
# include/linux/memblock.h:
"__init_memblock",
"__meminit",
# include/linux/init.h:
"__init",
"__ref",
# include/linux/linkage.h:
"asmlinkage",
# include/linux/btf.h
"__bpf_kfunc",
]
# Ensure that autosectionlabel will produce unique names
autosectionlabel_prefix_document = True
autosectionlabel_maxdepth = 2
# Load math renderer:
# For html builder, load imgmath only when its dependencies are met.
# mathjax is the default math renderer since Sphinx 1.8.
have_latex = have_command("latex")
have_dvipng = have_command("dvipng")
load_imgmath = have_latex and have_dvipng
# Respect SPHINX_IMGMATH (for html docs only)
if "SPHINX_IMGMATH" in os.environ:
env_sphinx_imgmath = os.environ["SPHINX_IMGMATH"]
if "yes" in env_sphinx_imgmath:
load_imgmath = True
elif "no" in env_sphinx_imgmath:
load_imgmath = False
else:
sys.stderr.write("Unknown env SPHINX_IMGMATH=%s ignored.\n" % env_sphinx_imgmath)
if load_imgmath:
extensions.append("sphinx.ext.imgmath")
math_renderer = "imgmath"
else:
math_renderer = "mathjax"
# Add any paths that contain templates here, relative to this directory.
templates_path = ["sphinx/templates"]
# The suffixes of source filenames that will be automatically parsed
source_suffix = {
".rst": "restructuredtext",
".yaml": "yaml",
}
# The encoding of source files.
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = "index"
# General information about the project.
project = "The Linux Kernel"
copyright = "The kernel development community" # pylint: disable=W0622
author = "The kernel development community"
# 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.
#
# In a normal build, version and release are set to KERNELVERSION and
# KERNELRELEASE, respectively, from the Makefile via Sphinx command line
# arguments.
#
# The following code tries to extract the information by reading the Makefile,
# when Sphinx is run directly (e.g. by Read the Docs).
try:
makefile_version = None
makefile_patchlevel = None
with open("../Makefile", encoding="utf=8") as fp:
for line in fp:
key, val = [x.strip() for x in line.split("=", 2)]
if key == "VERSION":
makefile_version = val
elif key == "PATCHLEVEL":
makefile_patchlevel = val
if makefile_version and makefile_patchlevel:
break
except Exception:
pass
finally:
if makefile_version and makefile_patchlevel:
version = release = makefile_version + "." + makefile_patchlevel
else:
version = release = "unknown version"
def get_cline_version():
"""
HACK: There seems to be no easy way for us to get at the version and
release information passed in from the makefile...so go pawing through the
command-line options and find it for ourselves.
"""
c_version = c_release = ""
for arg in sys.argv:
if arg.startswith("version="):
c_version = arg[8:]
elif arg.startswith("release="):
c_release = arg[8:]
if c_version:
if c_release:
return c_version + "-" + c_release
return c_version
return version # Whatever we came up with before
# 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'
# 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
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = "sphinx"
# 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
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
primary_domain = "c"
highlight_language = "none"
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
# Default theme
html_theme = "alabaster"
html_css_files = []
if "DOCS_THEME" in os.environ:
html_theme = os.environ["DOCS_THEME"]
if html_theme in ["sphinx_rtd_theme", "sphinx_rtd_dark_mode"]:
# Read the Docs theme
try:
import sphinx_rtd_theme
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
# 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_css_files = [
"theme_overrides.css",
]
# Read the Docs dark mode override theme
if html_theme == "sphinx_rtd_dark_mode":
try:
import sphinx_rtd_dark_mode # pylint: disable=W0611
extensions.append("sphinx_rtd_dark_mode")
except ImportError:
html_theme = "sphinx_rtd_theme"
if html_theme == "sphinx_rtd_theme":
# Add color-specific RTD normal mode
html_css_files.append("theme_rtd_colors.css")
html_theme_options = {
"navigation_depth": -1,
}
except ImportError:
html_theme = "alabaster"
if "DOCS_CSS" in os.environ:
css = os.environ["DOCS_CSS"].split(" ")
for l in css:
html_css_files.append(l)
if html_theme == "alabaster":
html_theme_options = {
"description": get_cline_version(),
"page_width": "65em",
"sidebar_width": "15em",
"fixed_sidebar": "true",
"font_size": "inherit",
"font_family": "serif",
}
sys.stderr.write("Using %s theme\n" % html_theme)
# 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 = ["sphinx-static"]
# If true, Docutils "smart quotes" will be used to convert quotes and dashes
# to typographically correct entities. However, conversion of "--" to "—"
# is not always what we want, so enable only quotes.
smartquotes_action = "q"
# Custom sidebar templates, maps document names to template names.
# Note that the RTD theme ignores this
html_sidebars = {"**": ["searchbox.html",
"kernel-toc.html",
"sourcelink.html"]}
# about.html is available for alabaster theme. Add it at the front.
if html_theme == "alabaster":
html_sidebars["**"].insert(0, "about.html")
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
html_logo = "images/logo.svg"
# Output file base name for HTML help builder.
htmlhelp_basename = "TheLinuxKerneldoc"
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
"papersize": "a4paper",
"passoptionstopackages": dedent(r"""
\PassOptionsToPackage{svgnames}{xcolor}
"""),
# The font size ('10pt', '11pt' or '12pt').
"pointsize": "11pt",
# Needed to generate a .ind file
"printindex": r"\footnotesize\raggedright\printindex",
# Latex figure (float) alignment
# 'figure_align': 'htbp',
# Don't mangle with UTF-8 chars
"fontenc": "",
"inputenc": "",
"utf8extra": "",
# Set document margins
"sphinxsetup": dedent(r"""
hmargin=0.5in, vmargin=1in,
parsedliteralwraps=true,
verbatimhintsturnover=false,
"""),
#
# Some of our authors are fond of deep nesting; tell latex to
# cope.
#
"maxlistdepth": "10",
# For CJK One-half spacing, need to be in front of hyperref
"extrapackages": r"\usepackage{setspace}",
"fontpkg": dedent(r"""
\usepackage{fontspec}
\setmainfont{DejaVu Serif}
\setsansfont{DejaVu Sans}
\setmonofont{DejaVu Sans Mono}
\newfontfamily\headingfont{DejaVu Serif}
"""),
"preamble": dedent(r"""
% Load kerneldoc specific LaTeX settings
\input{kerneldoc-preamble.sty}
""")
}
# This will be filled up by config-inited event
latex_documents = []
# The name of an image file (relative to this directory) to place at the top of
# the title page.
# latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
# latex_use_parts = False
# If true, show page references after internal links.
# latex_show_pagerefs = False
# If true, show URL addresses after external links.
# latex_show_urls = False
# Documents to append as an appendix to all manuals.
# latex_appendices = []
# If false, no module index is generated.
# latex_domain_indices = True
# Additional LaTeX stuff to be copied to build directory
latex_additional_files = [
"sphinx/kerneldoc-preamble.sty",
]
# -- 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, "thelinuxkernel", "The Linux Kernel Documentation", [author], 1)
]
# If true, show URL addresses after external links.
# man_show_urls = False
# -- 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,
"TheLinuxKernel",
"The Linux Kernel Documentation",
author,
"TheLinuxKernel",
"One line description of project.",
"Miscellaneous",
),]
# -- Options for Epub output ----------------------------------------------
# Bibliographic Dublin Core info.
epub_title = project
epub_author = author
epub_publisher = author
epub_copyright = copyright
# A list of files that should not be packed into the epub file.
epub_exclude_files = ["search.html"]
# =======
# rst2pdf
#
# Grouping the document tree into PDF files. List of tuples
# (source start file, target name, title, author, options).
#
# See the Sphinx chapter of https://ralsina.me/static/manual.pdf
#
# FIXME: Do not add the index file here; the result will be too big. Adding
# multiple PDF files here actually tries to get the cross-referencing right
# *between* PDF files.
pdf_documents = [
("kernel-documentation", "Kernel", "Kernel", "J. Random Bozo"),
]
# kernel-doc extension configuration for running Sphinx directly (e.g. by Read
# the Docs). In a normal build, these are supplied from the Makefile via command
# line arguments.
kerneldoc_bin = "../scripts/kernel-doc.py"
kerneldoc_srctree = ".."
# ------------------------------------------------------------------------------
# Since loadConfig overwrites settings from the global namespace, it has to be
# the last statement in the conf.py file
# ------------------------------------------------------------------------------
loadConfig(globals())
def setup(app):
"""Patterns need to be updated at init time on older Sphinx versions"""
app.connect('config-inited', config_init)
요약·해설
conf.py:1-596Linux 커널 Documentation 트리의 Sphinx 확장, 동적 포함·제외 패턴, 버전 추출, HTML·LaTeX·man·Texinfo·EPUB·PDF 출력과 초기화 후크를 정의하는 중앙 설정 파일을 해설합니다.
최소 Sphinx 3.4.3을 지원하면서 5.1의 include_patterns 유무를 분기하고, `loadConfig(globals())`로 외부 설정을 적용한 뒤 `config-inited` 이벤트에서 실제 SOURCEDIR 기준 경로와 LaTeX 문서 목록을 완성합니다.
입력 선택부터 각 출력 형식과 초기화 이벤트까지의 상위 흐름입니다.