docs: Correct Python coding style

This commit is contained in:
Roland Dobai 2018-12-01 09:25:08 +01:00
parent eb27686416
commit b56ed1a99e
9 changed files with 157 additions and 141 deletions

View file

@ -164,14 +164,6 @@ exclude =
components/ulp/esp32ulp_mapgen.py, components/ulp/esp32ulp_mapgen.py,
components/wifi_provisioning/python/wifi_config_pb2.py, components/wifi_provisioning/python/wifi_config_pb2.py,
components/wifi_provisioning/python/wifi_constants_pb2.py, components/wifi_provisioning/python/wifi_constants_pb2.py,
docs/conf_common.py,
docs/en/conf.py,
docs/gen-dxd.py,
docs/gen-toolchain-links.py,
docs/gen-version-specific-includes.py,
docs/link-roles.py,
docs/local_util.py,
docs/zh_CN/conf.py,
examples/peripherals/can/can_alert_and_recovery/example_test.py, examples/peripherals/can/can_alert_and_recovery/example_test.py,
examples/peripherals/can/can_network/example_test.py, examples/peripherals/can/can_network/example_test.py,
examples/peripherals/can/can_self_test/example_test.py, examples/peripherals/can/can_self_test/example_test.py,

View file

@ -16,10 +16,9 @@
from __future__ import print_function from __future__ import print_function
from __future__ import unicode_literals from __future__ import unicode_literals
import sys, os import sys
import re import os
import subprocess import subprocess
import shlex
# Note: If extensions (or modules to document with autodoc) are in another directory, # Note: 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 # add these directories to sys.path here. If the directory is relative to the
@ -41,11 +40,13 @@ try:
except KeyError: except KeyError:
idf_path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..')) idf_path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..'))
def call_with_python(cmd): def call_with_python(cmd):
# using sys.executable ensures that the scripts are called with the same Python interpreter # using sys.executable ensures that the scripts are called with the same Python interpreter
if os.system('{} {}'.format(sys.executable, cmd)) != 0: if os.system('{} {}'.format(sys.executable, cmd)) != 0:
raise RuntimeError('{} failed'.format(cmd)) raise RuntimeError('{} failed'.format(cmd))
# Call Doxygen to get XML files from the header files # Call Doxygen to get XML files from the header files
print("Calling Doxygen to generate latest XML files") print("Calling Doxygen to generate latest XML files")
if os.system("doxygen ../Doxyfile") != 0: if os.system("doxygen ../Doxyfile") != 0:
@ -58,6 +59,7 @@ copy_if_modified('xml/', 'xml_in/')
# Generate 'api_name.inc' files using the XML files by Doxygen # Generate 'api_name.inc' files using the XML files by Doxygen
call_with_python('../gen-dxd.py') call_with_python('../gen-dxd.py')
def find_component_files(parent_dir, target_filename): def find_component_files(parent_dir, target_filename):
parent_dir = os.path.abspath(parent_dir) parent_dir = os.path.abspath(parent_dir)
result = [] result = []
@ -73,6 +75,7 @@ def find_component_files(parent_dir, target_filename):
print("List of %s: %s" % (target_filename, ", ".join(result))) print("List of %s: %s" % (target_filename, ", ".join(result)))
return result return result
# Generate 'kconfig.inc' file from components' Kconfig files # Generate 'kconfig.inc' file from components' Kconfig files
print("Generating kconfig.inc from kconfig contents") print("Generating kconfig.inc from kconfig contents")
kconfig_inc_path = '{}/inc/kconfig.inc'.format(builddir) kconfig_inc_path = '{}/inc/kconfig.inc'.format(builddir)
@ -90,7 +93,7 @@ confgen_args = [sys.executable,
"--env", "COMPONENT_KCONFIGS_PROJBUILD={}".format(" ".join(kconfig_projbuilds)), "--env", "COMPONENT_KCONFIGS_PROJBUILD={}".format(" ".join(kconfig_projbuilds)),
"--env", "IDF_PATH={}".format(idf_path), "--env", "IDF_PATH={}".format(idf_path),
"--output", "docs", kconfig_inc_path + '.in' "--output", "docs", kconfig_inc_path + '.in'
] ]
subprocess.check_call(confgen_args) subprocess.check_call(confgen_args)
copy_if_modified(kconfig_inc_path + '.in', kconfig_inc_path) copy_if_modified(kconfig_inc_path + '.in', kconfig_inc_path)
@ -99,6 +102,7 @@ esp_err_inc_path = '{}/inc/esp_err_defs.inc'.format(builddir)
call_with_python('../../tools/gen_esp_err_to_name.py --rst_output ' + esp_err_inc_path + '.in') call_with_python('../../tools/gen_esp_err_to_name.py --rst_output ' + esp_err_inc_path + '.in')
copy_if_modified(esp_err_inc_path + '.in', esp_err_inc_path) copy_if_modified(esp_err_inc_path + '.in', esp_err_inc_path)
# Generate version-related includes # Generate version-related includes
# #
# (Note: this is in a function as it needs to access configuration to get the language) # (Note: this is in a function as it needs to access configuration to get the language)
@ -108,6 +112,7 @@ def generate_version_specific_includes(app):
call_with_python('../gen-version-specific-includes.py {} {}'.format(app.config.language, version_tmpdir)) call_with_python('../gen-version-specific-includes.py {} {}'.format(app.config.language, version_tmpdir))
copy_if_modified(version_tmpdir, '{}/inc'.format(builddir)) copy_if_modified(version_tmpdir, '{}/inc'.format(builddir))
# Generate toolchain download links # Generate toolchain download links
print("Generating toolchain download links") print("Generating toolchain download links")
base_url = 'https://dl.espressif.com/dl/' base_url = 'https://dl.espressif.com/dl/'
@ -116,26 +121,27 @@ call_with_python('../gen-toolchain-links.py ../../tools/toolchain_versions.mk {}
copy_if_modified(toolchain_tmpdir, '{}/inc'.format(builddir)) copy_if_modified(toolchain_tmpdir, '{}/inc'.format(builddir))
# http://stackoverflow.com/questions/12772927/specifying-an-online-image-in-sphinx-restructuredtext-format # http://stackoverflow.com/questions/12772927/specifying-an-online-image-in-sphinx-restructuredtext-format
# #
suppress_warnings = ['image.nonlocal_uri'] suppress_warnings = ['image.nonlocal_uri']
# -- General configuration ------------------------------------------------ # -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here. # If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0' # needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be # Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones. # ones.
extensions = ['breathe', extensions = ['breathe',
'link-roles', 'link-roles',
'sphinxcontrib.blockdiag', 'sphinxcontrib.blockdiag',
'sphinxcontrib.seqdiag', 'sphinxcontrib.seqdiag',
'sphinxcontrib.actdiag', 'sphinxcontrib.actdiag',
'sphinxcontrib.nwdiag', 'sphinxcontrib.nwdiag',
'sphinxcontrib.rackdiag', 'sphinxcontrib.rackdiag',
'sphinxcontrib.packetdiag' 'sphinxcontrib.packetdiag'
] ]
# Set up font for blockdiag, nwdiag, rackdiag and packetdiag # Set up font for blockdiag, nwdiag, rackdiag and packetdiag
blockdiag_fontpath = '../_static/DejaVuSans.ttf' blockdiag_fontpath = '../_static/DejaVuSans.ttf'
@ -153,7 +159,7 @@ seqdiag_antialias = True
# Doxygen regenerates files in 'xml/' directory every time, # Doxygen regenerates files in 'xml/' directory every time,
# but we copy files to 'xml_in/' only when they change, to speed up # but we copy files to 'xml_in/' only when they change, to speed up
# incremental builds. # incremental builds.
breathe_projects = { "esp32-idf": "xml_in/" } breathe_projects = {"esp32-idf": "xml_in/"}
breathe_default_project = "esp32-idf" breathe_default_project = "esp32-idf"
# Add any paths that contain templates here, relative to this directory. # Add any paths that contain templates here, relative to this directory.
@ -162,12 +168,11 @@ templates_path = ['_templates']
# The suffix of source filenames. # The suffix of source filenames.
source_suffix = ['.rst', '.md'] source_suffix = ['.rst', '.md']
source_parsers = { source_parsers = {'.md': 'recommonmark.parser.CommonMarkParser',
'.md': 'recommonmark.parser.CommonMarkParser', }
}
# The encoding of source files. # The encoding of source files.
#source_encoding = 'utf-8-sig' # source_encoding = 'utf-8-sig'
# The master toctree document. # The master toctree document.
master_doc = 'index' master_doc = 'index'
@ -192,9 +197,9 @@ print('Version: {0} Release: {1}'.format(version, release))
# There are two options for replacing |today|: either, you set today to some # There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used: # non-false value, then it is used:
#today = '' # today = ''
# Else, today_fmt is used as the format for a strftime call. # Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y' # today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and # List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files. # directories to ignore when looking for source files.
@ -202,27 +207,27 @@ exclude_patterns = ['_build','README.md']
# The reST default role (used for this markup: `text`) to use for all # The reST default role (used for this markup: `text`) to use for all
# documents. # documents.
#default_role = None # default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text. # If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True # add_function_parentheses = True
# If true, the current module name will be prepended to all description # If true, the current module name will be prepended to all description
# unit titles (such as .. function::). # unit titles (such as .. function::).
#add_module_names = True # add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the # If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default. # output. They are ignored by default.
#show_authors = False # show_authors = False
# The name of the Pygments (syntax highlighting) style to use. # The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx' pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting. # A list of ignored prefixes for module index sorting.
#modindex_common_prefix = [] # modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents. # If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False # keep_warnings = False
# -- Options for HTML output ---------------------------------------------- # -- Options for HTML output ----------------------------------------------
@ -234,17 +239,17 @@ html_theme = 'sphinx_rtd_theme'
# Theme options are theme-specific and customize the look and feel of a 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 # further. For a list of options available for each theme, see the
# documentation. # documentation.
#html_theme_options = {} # html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory. # Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = [] # html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to # The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation". # "<project> v<release> documentation".
#html_title = None # html_title = None
# A shorter title for the navigation bar. Default is the same as html_title. # A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None # html_short_title = None
# The name of an image file (relative to this directory) to place at the top # The name of an image file (relative to this directory) to place at the top
# of the sidebar. # of the sidebar.
@ -253,7 +258,7 @@ html_logo = "../_static/espressif-logo.svg"
# The name of an image file (within the static path) to use as favicon of the # The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large. # pixels large.
#html_favicon = None # html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here, # 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, # relative to this directory. They are copied after the builtin static files,
@ -263,48 +268,48 @@ html_static_path = ['../_static']
# Add any extra paths that contain custom files (such as robots.txt or # Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied # .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation. # directly to the root of the documentation.
#html_extra_path = [] # html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format. # using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y' # html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to # If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities. # typographically correct entities.
#html_use_smartypants = True # html_use_smartypants = True
# Custom sidebar templates, maps document names to template names. # Custom sidebar templates, maps document names to template names.
#html_sidebars = {} # html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to # Additional templates that should be rendered to pages, maps page names to
# template names. # template names.
#html_additional_pages = {} # html_additional_pages = {}
# If false, no module index is generated. # If false, no module index is generated.
#html_domain_indices = True # html_domain_indices = True
# If false, no index is generated. # If false, no index is generated.
#html_use_index = True # html_use_index = True
# If true, the index is split into individual pages for each letter. # If true, the index is split into individual pages for each letter.
#html_split_index = False # html_split_index = False
# If true, links to the reST sources are added to the pages. # If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True # html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True # html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True # html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will # If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the # contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served. # base URL from which the finished HTML is served.
#html_use_opensearch = '' # html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml"). # This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None # html_file_suffix = None
# Output file base name for HTML help builder. # Output file base name for HTML help builder.
htmlhelp_basename = 'ReadtheDocsTemplatedoc' htmlhelp_basename = 'ReadtheDocsTemplatedoc'
@ -313,43 +318,43 @@ htmlhelp_basename = 'ReadtheDocsTemplatedoc'
# -- Options for LaTeX output --------------------------------------------- # -- Options for LaTeX output ---------------------------------------------
latex_elements = { latex_elements = {
# The paper size ('letterpaper' or 'a4paper'). # The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper', # 'papersize': 'letterpaper',
#
# The font size ('10pt', '11pt' or '12pt'). # The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt', # 'pointsize': '10pt',
#
# Additional stuff for the LaTeX preamble. # Additional stuff for the LaTeX preamble.
#'preamble': '', # 'preamble': '',
} }
# Grouping the document tree into LaTeX files. List of tuples # Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, # (source start file, target name, title,
# author, documentclass [howto, manual, or own class]). # author, documentclass [howto, manual, or own class]).
latex_documents = [ latex_documents = [
('index', 'ReadtheDocsTemplate.tex', u'Read the Docs Template Documentation', ('index', 'ReadtheDocsTemplate.tex', u'Read the Docs Template Documentation',
u'Read the Docs', 'manual'), u'Read the Docs', 'manual'),
] ]
# The name of an image file (relative to this directory) to place at the top of # The name of an image file (relative to this directory) to place at the top of
# the title page. # the title page.
#latex_logo = None # latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts, # For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters. # not chapters.
#latex_use_parts = False # latex_use_parts = False
# If true, show page references after internal links. # If true, show page references after internal links.
#latex_show_pagerefs = False # latex_show_pagerefs = False
# If true, show URL addresses after external links. # If true, show URL addresses after external links.
#latex_show_urls = False # latex_show_urls = False
# Documents to append as an appendix to all manuals. # Documents to append as an appendix to all manuals.
#latex_appendices = [] # latex_appendices = []
# If false, no module index is generated. # If false, no module index is generated.
#latex_domain_indices = True # latex_domain_indices = True
# -- Options for manual page output --------------------------------------- # -- Options for manual page output ---------------------------------------
@ -362,7 +367,7 @@ man_pages = [
] ]
# If true, show URL addresses after external links. # If true, show URL addresses after external links.
#man_show_urls = False # man_show_urls = False
# -- Options for Texinfo output ------------------------------------------- # -- Options for Texinfo output -------------------------------------------
@ -371,22 +376,23 @@ man_pages = [
# (source start file, target name, title, author, # (source start file, target name, title, author,
# dir menu entry, description, category) # dir menu entry, description, category)
texinfo_documents = [ texinfo_documents = [
('index', 'ReadtheDocsTemplate', u'Read the Docs Template Documentation', ('index', 'ReadtheDocsTemplate', u'Read the Docs Template Documentation',
u'Read the Docs', 'ReadtheDocsTemplate', 'One line description of project.', u'Read the Docs', 'ReadtheDocsTemplate', 'One line description of project.',
'Miscellaneous'), 'Miscellaneous'),
] ]
# Documents to append as an appendix to all manuals. # Documents to append as an appendix to all manuals.
#texinfo_appendices = [] # texinfo_appendices = []
# If false, no module index is generated. # If false, no module index is generated.
#texinfo_domain_indices = True # texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'. # How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote' # texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu. # If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False # texinfo_no_detailmenu = False
# Override RTD CSS theme to introduce the theme corrections # Override RTD CSS theme to introduce the theme corrections
# https://github.com/rtfd/sphinx_rtd_theme/pull/432 # https://github.com/rtfd/sphinx_rtd_theme/pull/432

View file

@ -6,9 +6,10 @@
# Importing conf_common adds all the non-language-specific # Importing conf_common adds all the non-language-specific
# parts to this conf module # parts to this conf module
import sys, os import sys
import os
sys.path.insert(0, os.path.abspath('..')) sys.path.insert(0, os.path.abspath('..'))
from conf_common import * from conf_common import * # noqa: F401, F403 - need to make available everything from common
# General information about the project. # General information about the project.
project = u'ESP-IDF Programming Guide' project = u'ESP-IDF Programming Guide'

View file

@ -41,7 +41,7 @@ all_kinds = [
("define", "Macros"), ("define", "Macros"),
("typedef", "Type Definitions"), ("typedef", "Type Definitions"),
("enum", "Enumerations") ("enum", "Enumerations")
] ]
"""list of items that will be generated for a single API file """list of items that will be generated for a single API file
""" """
@ -78,7 +78,7 @@ def get_doxyfile_input():
# process only lines that are not comments # process only lines that are not comments
if line.find("#") == -1: if line.find("#") == -1:
# extract header file path inside components folder # extract header file path inside components folder
m = re.search(header_file_path_prefix + "(.*\.h)", line) m = re.search(header_file_path_prefix + "(.*\.h)", line) # noqa: W605 - regular expression
header_file_path = m.group(1) header_file_path = m.group(1)
doxyfile_INPUT += header_file_path + "\n" doxyfile_INPUT += header_file_path + "\n"
# proceed reading next line # proceed reading next line

View file

@ -10,6 +10,7 @@ from __future__ import print_function
import sys import sys
import os import os
def main(): def main():
if len(sys.argv) != 4: if len(sys.argv) != 4:
print("Usage: gen-toolchain-links.py <versions file> <base download URL> <output directory>") print("Usage: gen-toolchain-links.py <versions file> <base download URL> <output directory>")
@ -48,10 +49,10 @@ def main():
./bootstrap && ./configure --enable-local && make install ./bootstrap && ./configure --enable-local && make install
""" """
platform_info = [ ["linux64", "tar.gz", "z", unpack_code_linux_macos], platform_info = [["linux64", "tar.gz", "z", unpack_code_linux_macos],
["linux32", "tar.gz", "z", unpack_code_linux_macos], ["linux32", "tar.gz", "z", unpack_code_linux_macos],
["osx", "tar.gz", "z", unpack_code_linux_macos], ["osx", "tar.gz", "z", unpack_code_linux_macos],
["win32", "zip", None, None]] ["win32", "zip", None, None]]
with open(os.path.join(out_dir, 'download-links.inc'), "w") as links_file: with open(os.path.join(out_dir, 'download-links.inc'), "w") as links_file:
for p in platform_info: for p in platform_info:
@ -61,8 +62,8 @@ def main():
unpack_code = p[3] unpack_code = p[3]
archive_name = 'xtensa-esp32-elf-{}-{}-{}.{}'.format( archive_name = 'xtensa-esp32-elf-{}-{}-{}.{}'.format(
platform_name, toolchain_desc, gcc_version, extension) platform_name, toolchain_desc, gcc_version, extension)
print('.. |download_link_{}| replace:: {}{}'.format( print('.. |download_link_{}| replace:: {}{}'.format(
platform_name, base_url, archive_name), file=links_file) platform_name, base_url, archive_name), file=links_file)
@ -73,5 +74,6 @@ def main():
with open(os.path.join(out_dir, 'scratch-build-code.inc'), "w") as code_file: with open(os.path.join(out_dir, 'scratch-build-code.inc'), "w") as code_file:
print(scratch_build_code_linux_macos, file=code_file) print(scratch_build_code_linux_macos, file=code_file)
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View file

@ -13,9 +13,9 @@ import sys
import re import re
TEMPLATES = { TEMPLATES = {
"en" : { "en": {
"git-clone" : { "git-clone": {
"template" : """ "template": """
To obtain a local copy: open terminal, navigate to the directory you want to put ESP-IDF, and clone the repository using ``git clone`` command:: To obtain a local copy: open terminal, navigate to the directory you want to put ESP-IDF, and clone the repository using ``git clone`` command::
cd ~/esp cd ~/esp
@ -30,32 +30,37 @@ ESP-IDF will be downloaded into ``~/esp/esp-idf``.
.. note:: .. note::
%(zipfile_note)s %(zipfile_note)s
""" """,
,"master" : 'This command will clone the master branch, which has the latest development ("bleeding edge") version of ESP-IDF. It is fully functional and updated on weekly basis with the most recent features and bugfixes.' "master": 'This command will clone the master branch, which has the latest development ("bleeding edge") '
,"branch" : 'The ``git clone`` option ``-b %(clone_arg)s`` tells git to clone the %(ver_type)s in the ESP-IDF repository corresponding to this version of the documentation.' 'version of ESP-IDF. It is fully functional and updated on weekly basis with the most recent features and bugfixes.',
,"zipfile" : { "branch": 'The ``git clone`` option ``-b %(clone_arg)s`` tells git to clone the %(ver_type)s in the ESP-IDF repository '
"stable" : 'As a fallback, it is also possible to download a zip file of this stable release from the `Releases page`_. Do not download the "Source code" zip file(s) generated automatically by GitHub, they do not work with ESP-IDF.' 'corresponding to this version of the documentation.',
,"unstable" : 'GitHub\'s "Download zip file" feature does not work with ESP-IDF, a ``git clone`` is required. As a fallback, `Stable version`_ can be installed without Git.' "zipfile": {
}, # zipfile "stable": 'As a fallback, it is also possible to download a zip file of this stable release from the `Releases page`_. '
}, # git-clone 'Do not download the "Source code" zip file(s) generated automatically by GitHub, they do not work with ESP-IDF.',
"version-note" : { "unstable": 'GitHub\'s "Download zip file" feature does not work with ESP-IDF, a ``git clone`` is required. As a fallback, '
"master" : """ '`Stable version`_ can be installed without Git.'
}, # zipfile
}, # git-clone
"version-note": {
"master": """
.. note:: .. note::
This is documentation for the master branch (latest version) of ESP-IDF. This version is under continual development. `Stable version`_ documentation is available, as well as other :doc:`/versions`. This is documentation for the master branch (latest version) of ESP-IDF. This version is under continual development.
""" `Stable version`_ documentation is available, as well as other :doc:`/versions`.
,"stable" : """ """,
"stable": """
.. note:: .. note::
This is documentation for stable version %s of ESP-IDF. Other :doc:`/versions` are also available. This is documentation for stable version %s of ESP-IDF. Other :doc:`/versions` are also available.
""" """,
,"branch" : """ "branch": """
.. note:: .. note::
This is documentation for %s ``%s`` of ESP-IDF. Other :doc:`/versions` are also available. This is documentation for %s ``%s`` of ESP-IDF. Other :doc:`/versions` are also available.
""" """
}, # version-note }, # version-note
}, # en }, # en
"zh_CN" : { "zh_CN": {
"git-clone" : { "git-clone": {
"template" : """ "template": """
获取本地副本打开终端切换到你要存放 ESP-IDF 的工作目录使用 ``git clone`` 命令克隆远程仓库:: 获取本地副本打开终端切换到你要存放 ESP-IDF 的工作目录使用 ``git clone`` 命令克隆远程仓库::
cd ~/esp cd ~/esp
@ -70,30 +75,32 @@ ESP-IDF 将会被下载到 ``~/esp/esp-idf`` 目录下。
.. note:: .. note::
%(zipfile_note)s %(zipfile_note)s
""" """,
,"master" : '此命令将克隆 master 分支,该分支保存着 ESP-IDF 的最新版本,它功能齐全,每周都会更新一些新功能并修正一些错误。' "master": '此命令将克隆 master 分支,该分支保存着 ESP-IDF 的最新版本,它功能齐全,每周都会更新一些新功能并修正一些错误。',
,"branch" : '``git clone`` 命令的 ``-b %(clone_arg)s`` 选项告诉 git 从 ESP-IDF 仓库中克隆与此版本的文档对应的分支。' "branch": '``git clone`` 命令的 ``-b %(clone_arg)s`` 选项告诉 git 从 ESP-IDF 仓库中克隆与此版本的文档对应的分支。',
,"zipfile" : { "zipfile": {
"stable" : '作为备份,还可以从 `Releases page`_ 下载此稳定版本的 zip 文件。不要下载由 GitHub 自动生成的"源代码"的 zip 文件,它们不适用于 ESP-IDF。' "stable": '作为备份,还可以从 `Releases page`_ 下载此稳定版本的 zip 文件。不要下载由 GitHub 自动生成的"源代码"的 zip 文件,它们不适用于 ESP-IDF。',
,"unstable" : 'GitHub 中"下载 zip 文档"的功能不适用于 ESP-IDF所以需要使用 ``git clone`` 命令。作为备份,可以在没有安装 Git 的环境中下载 `Stable version`_ 的 zip 归档文件。' "unstable": 'GitHub 中"下载 zip 文档"的功能不适用于 ESP-IDF所以需要使用 ``git clone`` 命令。作为备份,可以在没有安装 Git 的环境中下载 '
}, # zipfile '`Stable version`_ 的 zip 归档文件。'
}, # git-clone }, # zipfile
"version-note" : { }, # git-clone
"master" : """ "version-note": {
"master": """
.. note:: .. note::
这是ESP-IDF master 分支最新版本的文档该版本在持续开发中还有 `Stable version`_ 的文档以及其他版本的文档 :doc:`/versions` 供参考 这是ESP-IDF master 分支最新版本的文档该版本在持续开发中还有 `Stable version`_ 的文档以及其他版本的文档 :doc:`/versions` 供参考
This is documentation for the master branch (latest version) of ESP-IDF. This version is under continual development. `Stable version`_ documentation is available, as well as other :doc:`/versions`. This is documentation for the master branch (latest version) of ESP-IDF. This version is under continual development. `Stable version`_ documentation is '
""" 'available, as well as other :doc:`/versions`.
,"stable" : """ """,
"stable": """
.. note:: .. note::
这是ESP-IDF 稳定版本 %s 的文档还有其他版本的文档 :doc:`/versions` 供参考 这是ESP-IDF 稳定版本 %s 的文档还有其他版本的文档 :doc:`/versions` 供参考
""" """,
,"branch" : """ "branch": """
.. note:: .. note::
这是ESP-IDF %s ``%s`` 版本的文档还有其他版本的文档 :doc:`/versions` 供参考 这是ESP-IDF %s ``%s`` 版本的文档还有其他版本的文档 :doc:`/versions` 供参考
""" """
}, # version-note }, # version-note
}# zh_CN } # zh_CN
} }
@ -121,15 +128,15 @@ def write_git_clone_inc(template, out_dir, version, ver_type, is_stable):
zipfile = template["zipfile"] zipfile = template["zipfile"]
if version == "master": if version == "master":
args = { args = {
"clone_args" : "", "clone_args": "",
"extra_note" : template["master"], "extra_note": template["master"],
"zipfile_note" : zipfile["unstable"] "zipfile_note": zipfile["unstable"]
} }
else: else:
args = { args = {
"clone_args" : "-b %s " % version, "clone_args": "-b %s " % version,
"extra_note" : template["branch"] % {"clone_arg" : version, "ver_type" : ver_type}, "extra_note": template["branch"] % {"clone_arg": version, "ver_type": ver_type},
"zipfile_note" : zipfile["stable"] if is_stable else zipfile["unstable"] "zipfile_note": zipfile["stable"] if is_stable else zipfile["unstable"]
} }
out_file = os.path.join(out_dir, "git-clone.inc") out_file = os.path.join(out_dir, "git-clone.inc")
with open(out_file, "w", encoding='utf-8') as f: with open(out_file, "w", encoding='utf-8') as f:
@ -172,7 +179,7 @@ def get_version():
print("refs:\n%s" % refs) print("refs:\n%s" % refs)
refs = refs.split(b"\n") refs = refs.split(b"\n")
# Note: this looks for branches in 'origin' because GitLab CI doesn't check out a local branch # Note: this looks for branches in 'origin' because GitLab CI doesn't check out a local branch
branches = [ r.replace(b"refs/remotes/origin/",b"").strip() for r in refs if r.startswith(b"refs/remotes/origin/") ] branches = [r.replace(b"refs/remotes/origin/",b"").strip() for r in refs if r.startswith(b"refs/remotes/origin/")]
if len(branches) == 0: if len(branches) == 0:
# last resort, return the commit (may happen on Gitlab CI sometimes, unclear why) # last resort, return the commit (may happen on Gitlab CI sometimes, unclear why)
return (subprocess.check_output(["git", "rev-parse", "--short", "HEAD"]).strip(), "commit", False) return (subprocess.check_output(["git", "rev-parse", "--short", "HEAD"]).strip(), "commit", False)
@ -181,5 +188,6 @@ def get_version():
else: else:
return (branches[0], "branch", False) # take whatever the first branch is return (branches[0], "branch", False) # take whatever the first branch is
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View file

@ -7,6 +7,7 @@ import os
from docutils import nodes from docutils import nodes
from local_util import run_cmd_get_output from local_util import run_cmd_get_output
def get_github_rev(): def get_github_rev():
path = run_cmd_get_output('git rev-parse --short HEAD') path = run_cmd_get_output('git rev-parse --short HEAD')
tag = run_cmd_get_output('git describe --exact-match') tag = run_cmd_get_output('git describe --exact-match')
@ -16,6 +17,7 @@ def get_github_rev():
path = tag path = tag
return path return path
def setup(app): def setup(app):
rev = get_github_rev() rev = get_github_rev()
@ -39,14 +41,15 @@ def setup(app):
if (run_cmd_get_output('git rev-parse --short HEAD') != rev): if (run_cmd_get_output('git rev-parse --short HEAD') != rev):
tag_rev = rev tag_rev = rev
else: else:
# if not on the RTD then provide generic identification # if not on the RTD then provide generic identification
tag_rev = run_cmd_get_output('git describe --always') tag_rev = run_cmd_get_output('git describe --always')
app.add_role('link_to_translation', crosslink('%s../../%s/{}/%s.html'.format(tag_rev))) app.add_role('link_to_translation', crosslink('%s../../%s/{}/%s.html'.format(tag_rev)))
def autolink(pattern): def autolink(pattern):
def role(name, rawtext, text, lineno, inliner, options={}, content=[]): def role(name, rawtext, text, lineno, inliner, options={}, content=[]):
m = re.search('(.*)\s*<(.*)>', text) m = re.search('(.*)\s*<(.*)>', text) # noqa: W605 - regular expression
if m: if m:
link_text = m.group(1) link_text = m.group(1)
link = m.group(2) link = m.group(2)
@ -58,12 +61,13 @@ def autolink(pattern):
return [node], [] return [node], []
return role return role
def crosslink(pattern): def crosslink(pattern):
def role(name, rawtext, text, lineno, inliner, options={}, content=[]): def role(name, rawtext, text, lineno, inliner, options={}, content=[]):
(language, link_text) = text.split(':') (language, link_text) = text.split(':')
docname = inliner.document.settings.env.docname docname = inliner.document.settings.env.docname
doc_path = inliner.document.settings.env.doc2path(docname, None, None) doc_path = inliner.document.settings.env.doc2path(docname, None, None)
return_path = '../' * doc_path.count('/') return_path = '../' * doc_path.count('/')
url = pattern % (return_path, language, docname) url = pattern % (return_path, language, docname)
node = nodes.reference(rawtext, link_text, refuri=url, **options) node = nodes.reference(rawtext, link_text, refuri=url, **options)
return [node], [] return [node], []

View file

@ -16,13 +16,14 @@
from __future__ import unicode_literals from __future__ import unicode_literals
from io import open from io import open
import re
import os import os
import shutil import shutil
def run_cmd_get_output(cmd): def run_cmd_get_output(cmd):
return os.popen(cmd).read().strip() return os.popen(cmd).read().strip()
def files_equal(path_1, path_2): def files_equal(path_1, path_2):
if not os.path.exists(path_1) or not os.path.exists(path_2): if not os.path.exists(path_1) or not os.path.exists(path_2):
return False return False
@ -34,6 +35,7 @@ def files_equal(path_1, path_2):
file_2_contents = f_2.read() file_2_contents = f_2.read()
return file_1_contents == file_2_contents return file_1_contents == file_2_contents
def copy_file_if_modified(src_file_path, dst_file_path): def copy_file_if_modified(src_file_path, dst_file_path):
if not files_equal(src_file_path, dst_file_path): if not files_equal(src_file_path, dst_file_path):
dst_dir_name = os.path.dirname(dst_file_path) dst_dir_name = os.path.dirname(dst_file_path)
@ -41,6 +43,7 @@ def copy_file_if_modified(src_file_path, dst_file_path):
os.makedirs(dst_dir_name) os.makedirs(dst_dir_name)
shutil.copy(src_file_path, dst_file_path) shutil.copy(src_file_path, dst_file_path)
def copy_if_modified(src_path, dst_path): def copy_if_modified(src_path, dst_path):
if os.path.isfile(src_path): if os.path.isfile(src_path):
copy_file_if_modified(src_path, dst_path) copy_file_if_modified(src_path, dst_path)
@ -52,4 +55,3 @@ def copy_if_modified(src_path, dst_path):
src_file_path = os.path.join(root, src_file_name) src_file_path = os.path.join(root, src_file_name)
dst_file_path = os.path.join(dst_path + root[src_path_len:], src_file_name) dst_file_path = os.path.join(dst_path + root[src_path_len:], src_file_name)
copy_file_if_modified(src_file_path, dst_file_path) copy_file_if_modified(src_file_path, dst_file_path)

View file

@ -6,9 +6,10 @@
# Importing conf_common adds all the non-language-specific # Importing conf_common adds all the non-language-specific
# parts to this conf module # parts to this conf module
import sys, os import sys
import os
sys.path.insert(0, os.path.abspath('..')) sys.path.insert(0, os.path.abspath('..'))
from conf_common import * from conf_common import * # noqa: F401, F403 - need to make available everything from common
# General information about the project. # General information about the project.
project = u'ESP-IDF 编程指南' project = u'ESP-IDF 编程指南'