pre-commit: Add ruff, ruff-format

Change-Id: Ic4e860a2517adecda8d15802bb2015c805869fa7
Signed-off-by: Stephen Finucane <stephenfin@redhat.com>
This commit is contained in:
Stephen Finucane 2024-08-29 10:42:40 +01:00
parent 9baeee486a
commit 2f49a663e6
9 changed files with 134 additions and 74 deletions

View File

@ -18,6 +18,12 @@ repos:
- id: debug-statements - id: debug-statements
- id: check-yaml - id: check-yaml
files: .*\.(yaml|yml)$ files: .*\.(yaml|yml)$
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.6.2
hooks:
- id: ruff
args: ['--fix']
- id: ruff-format
- repo: https://opendev.org/openstack/hacking - repo: https://opendev.org/openstack/hacking
rev: 7.0.0 rev: 7.0.0
hooks: hooks:

View File

@ -28,10 +28,7 @@
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones. # ones.
extensions = [ extensions = ['os_api_ref', 'openstackdocstheme']
'os_api_ref',
'openstackdocstheme'
]
# The suffix of source filenames. # The suffix of source filenames.
@ -44,8 +41,8 @@ master_doc = 'index'
# 'security guide' or 'network guide' # 'security guide' or 'network guide'
# It's used by the "log-a-bug" button on each page # It's used by the "log-a-bug" button on each page
# and should ultimately be set automatically by the build process # and should ultimately be set automatically by the build process
project = u'Test API Reference' project = 'Test API Reference'
copyright = u'2018, OpenStack Contributors' copyright = '2018, OpenStack Contributors'
# The version info for the project you're documenting, acts as replacement for # The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the # |version| and |release|, also used in various other places throughout the
@ -84,6 +81,8 @@ html_theme = 'openstackdocs'
# variable, sidebar_dropdown, should be set to `api_ref`. # variable, sidebar_dropdown, should be set to `api_ref`.
# Otherwise, the list of links for the User and Ops docs # Otherwise, the list of links for the User and Ops docs
# appear in the sidebar dropdown menu. # appear in the sidebar dropdown menu.
html_theme_options = {"sidebar_dropdown": "api_ref", html_theme_options = {
"display_badge": False, "sidebar_dropdown": "api_ref",
"sidebar_mode": "toc"} "display_badge": False,
"sidebar_mode": "toc",
}

View File

@ -35,7 +35,7 @@ source_suffix = '.rst'
master_doc = 'index' master_doc = 'index'
# General information about the project. # General information about the project.
copyright = u'2015-2018, OpenStack Contributors' copyright = '2015-2018, OpenStack Contributors'
# 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.
@ -60,9 +60,7 @@ html_theme = 'openstackdocs'
# variable, sidebar_dropdown, should be set to `api_ref`. # variable, sidebar_dropdown, should be set to `api_ref`.
# Otherwise, the list of links for the User and Ops docs # Otherwise, the list of links for the User and Ops docs
# appear in the sidebar dropdown menu. # appear in the sidebar dropdown menu.
html_theme_options = { html_theme_options = {'show_other_versions': True}
'show_other_versions': True
}
# 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,
@ -76,7 +74,11 @@ html_static_path = ['_static/css']
# (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', 'doc-openstackdocstheme.tex', (
u'OpenStack Docs Theme Documentation', 'index',
u'OpenStack Contributors', 'manual'), 'doc-openstackdocstheme.tex',
'OpenStack Docs Theme Documentation',
'OpenStack Contributors',
'manual',
),
] ]

View File

@ -69,8 +69,9 @@ def _get_other_versions(app):
refs = repo.get_refs() refs = repo.get_refs()
for ref in refs.keys(): for ref in refs.keys():
ref = ref.decode('utf-8') ref = ref.decode('utf-8')
if (ref.startswith('refs/remotes/origin/stable') or if ref.startswith('refs/remotes/origin/stable') or ref.startswith(
ref.startswith('refs/remotes/origin/unmaintained')): 'refs/remotes/origin/unmaintained'
):
series = ref.rpartition('/')[-1] series = ref.rpartition('/')[-1]
all_series.append(series) all_series.append(series)
elif ref.startswith('refs/tags/') and ref.endswith('-eol'): elif ref.startswith('refs/tags/') and ref.endswith('-eol'):
@ -86,9 +87,10 @@ def _get_other_versions(app):
# automatically include everything they actually have available # automatically include everything they actually have available
# because the start point is not present in the list. # because the start point is not present in the list.
earliest_desired = app.config.html_theme_options.get( earliest_desired = app.config.html_theme_options.get(
'earliest_published_series', 'zed') 'earliest_published_series', 'zed'
)
if earliest_desired and earliest_desired in all_series: if earliest_desired and earliest_desired in all_series:
interesting_series = all_series[all_series.index(earliest_desired):] interesting_series = all_series[all_series.index(earliest_desired) :]
else: else:
interesting_series = all_series interesting_series = all_series
@ -127,7 +129,8 @@ def _html_page_context(app, pagename, templatename, context, doctree):
"[openstackdocstheme] " "[openstackdocstheme] "
"the 'repository_name' config option has been deprecated and " "the 'repository_name' config option has been deprecated and "
"replaced by the 'openstackdocs_repo_name' option; support " "replaced by the 'openstackdocs_repo_name' option; support "
"for the former will be dropped in a future release") "for the former will be dropped in a future release"
)
app.config.openstackdocs_repo_name = app.config.repository_name app.config.openstackdocs_repo_name = app.config.repository_name
if app.config.use_storyboard is not None: if app.config.use_storyboard is not None:
@ -135,7 +138,8 @@ def _html_page_context(app, pagename, templatename, context, doctree):
"[openstackdocstheme] " "[openstackdocstheme] "
"the 'use_storyboard' config option has been deprecated and " "the 'use_storyboard' config option has been deprecated and "
"replaced by the 'openstackdocs_use_storyboard' option; " "replaced by the 'openstackdocs_use_storyboard' option; "
"support for the former will be dropped in a future release") "support for the former will be dropped in a future release"
)
app.config.openstackdocs_use_storyboard = app.config.use_storyboard app.config.openstackdocs_use_storyboard = app.config.use_storyboard
if app.config.bug_project is not None: if app.config.bug_project is not None:
@ -143,7 +147,8 @@ def _html_page_context(app, pagename, templatename, context, doctree):
"[openstackdocstheme] " "[openstackdocstheme] "
"the 'bug_project' config option has been deprecated and " "the 'bug_project' config option has been deprecated and "
"replaced by the 'openstackdocs_bug_project' option; support " "replaced by the 'openstackdocs_bug_project' option; support "
"for the former will be dropped in a future release") "for the former will be dropped in a future release"
)
app.config.openstackdocs_bug_project = app.config.bug_project app.config.openstackdocs_bug_project = app.config.bug_project
if app.config.bug_tag is not None: if app.config.bug_tag is not None:
@ -151,14 +156,19 @@ def _html_page_context(app, pagename, templatename, context, doctree):
"[openstackdocstheme] " "[openstackdocstheme] "
"the 'bug_tag' config option has been deprecated and " "the 'bug_tag' config option has been deprecated and "
"replaced by the 'openstackdocs_bug_tag' option; support " "replaced by the 'openstackdocs_bug_tag' option; support "
"for the former will be dropped in a future release") "for the former will be dropped in a future release"
)
app.config.openstackdocs_bug_project = app.config.bug_project app.config.openstackdocs_bug_project = app.config.bug_project
_html_context_data = {} _html_context_data = {}
try: try:
_html_context_data['gitsha'] = subprocess.check_output( _html_context_data['gitsha'] = (
['git', 'rev-parse', 'HEAD'], subprocess.check_output(
).decode('utf-8').strip() ['git', 'rev-parse', 'HEAD'],
)
.decode('utf-8')
.strip()
)
except Exception: except Exception:
logger.warning( logger.warning(
'[openstackdocstheme] cannot get gitsha from git repository' '[openstackdocstheme] cannot get gitsha from git repository'
@ -172,7 +182,8 @@ def _html_page_context(app, pagename, templatename, context, doctree):
if repo_name and doc_path: if repo_name and doc_path:
_html_context_data['giturl'] = _giturl.format(repo_name, doc_path) _html_context_data['giturl'] = _giturl.format(repo_name, doc_path)
logger.debug( logger.debug(
'[openstackdocstheme] giturl %r', _html_context_data['giturl'], '[openstackdocstheme] giturl %r',
_html_context_data['giturl'],
) )
use_storyboard = app.config.openstackdocs_use_storyboard use_storyboard = app.config.openstackdocs_use_storyboard
@ -181,7 +192,8 @@ def _html_page_context(app, pagename, templatename, context, doctree):
bug_project = app.config.openstackdocs_bug_project bug_project = app.config.openstackdocs_bug_project
if bug_project: if bug_project:
logger.debug( logger.debug(
'[openstackdocstheme] bug_project (from user) %r', bug_project, '[openstackdocstheme] bug_project (from user) %r',
bug_project,
) )
elif use_storyboard: elif use_storyboard:
bug_project = repo_name bug_project = repo_name
@ -209,12 +221,14 @@ def _html_page_context(app, pagename, templatename, context, doctree):
_html_context_data['pdf_link'] = app.config.openstackdocs_pdf_link _html_context_data['pdf_link'] = app.config.openstackdocs_pdf_link
logger.debug( logger.debug(
'[openstackdocstheme] pdf_link %r', _html_context_data['pdf_link'], '[openstackdocstheme] pdf_link %r',
_html_context_data['pdf_link'],
) )
if app.config.openstackdocs_pdf_filename: if app.config.openstackdocs_pdf_filename:
_html_context_data['pdf_filename'] = ( _html_context_data['pdf_filename'] = (
app.config.openstackdocs_pdf_filename) app.config.openstackdocs_pdf_filename
)
else: else:
short_repo_name = repo_name.split('/')[-1] short_repo_name = repo_name.split('/')[-1]
_html_context_data['pdf_filename'] = f'doc-{short_repo_name}.pdf' _html_context_data['pdf_filename'] = f'doc-{short_repo_name}.pdf'
@ -227,7 +241,8 @@ def _html_page_context(app, pagename, templatename, context, doctree):
_html_context_data['series'] = _get_series_name() _html_context_data['series'] = _get_series_name()
logger.debug( logger.debug(
'[openstackdocstheme] series %r', _html_context_data['series'], '[openstackdocstheme] series %r',
_html_context_data['series'],
) )
# Do not show the badge in these cases: # Do not show the badge in these cases:
@ -262,7 +277,8 @@ def _html_page_context(app, pagename, templatename, context, doctree):
context.update(_html_context_data) context.update(_html_context_data)
context['other_versions'] = _get_other_versions(app) context['other_versions'] = _get_other_versions(app)
logger.debug( logger.debug(
'[openstackdocstheme] other_versions %s', context['other_versions'], '[openstackdocstheme] other_versions %s',
context['other_versions'],
) )
@ -271,9 +287,13 @@ def _get_series_name():
global _series global _series
if _series is None: if _series is None:
try: try:
git_root_dir = subprocess.check_output( git_root_dir = (
['git', 'rev-parse', '--show-toplevel'], subprocess.check_output(
).decode('utf-8').strip() ['git', 'rev-parse', '--show-toplevel'],
)
.decode('utf-8')
.strip()
)
except Exception: except Exception:
logger.info( logger.info(
'[openstackdocstheme] cannot find git top directory, ' '[openstackdocstheme] cannot find git top directory, '
@ -301,7 +321,8 @@ def _setup_link_roles(app):
series = _get_series_name() series = _get_series_name()
for project_name in app.config.openstackdocs_projects: for project_name in app.config.openstackdocs_projects:
url = 'https://docs.openstack.org/{}/{}/%s'.format( url = 'https://docs.openstack.org/{}/{}/%s'.format(
project_name, series) project_name, series
)
role_name = '{}-doc'.format(project_name) role_name = '{}-doc'.format(project_name)
logger.debug( logger.debug(
'[openstackdocstheme] adding role %s to link to %s', '[openstackdocstheme] adding role %s to link to %s',
@ -327,8 +348,9 @@ def _find_setup_cfg(srcdir):
# an sdist or wheel? Perhaps we should check for 'PKG-INFO' or # an sdist or wheel? Perhaps we should check for 'PKG-INFO' or
# 'METADATA' files, a la 'pbr.packaging._get_version_from_pkg_metadata' # 'METADATA' files, a la 'pbr.packaging._get_version_from_pkg_metadata'
for path in [ for path in [
os.path.join(srcdir, os.pardir, 'setup.cfg'), os.path.join(srcdir, os.pardir, 'setup.cfg'),
os.path.join(srcdir, os.pardir, os.pardir, 'setup.cfg')]: os.path.join(srcdir, os.pardir, os.pardir, 'setup.cfg'),
]:
if os.path.exists(path): if os.path.exists(path):
return path return path
@ -374,7 +396,6 @@ def _get_project_name(srcdir):
def _config_inited(app, config): def _config_inited(app, config):
if config.openstack_projects is not None: if config.openstack_projects is not None:
logger.info( logger.info(
"[openstackdocstheme] " "[openstackdocstheme] "
@ -398,7 +419,8 @@ def _config_inited(app, config):
"overriding configured project name (%s) with name extracted " "overriding configured project name (%s) with name extracted "
"from the package (%s); you can disable this behavior with " "from the package (%s); you can disable this behavior with "
"the 'openstackdocs_auto_name' option", "the 'openstackdocs_auto_name' option",
config.project, project_name, config.project,
project_name,
) )
if project_name: if project_name:
@ -449,7 +471,6 @@ def _config_inited(app, config):
def _builder_inited(app): def _builder_inited(app):
theme_dir = paths.get_html_theme_path() theme_dir = paths.get_html_theme_path()
logger.info('[openstackdocstheme] using theme from %s', theme_dir) logger.info('[openstackdocstheme] using theme from %s', theme_dir)

View File

@ -31,13 +31,21 @@ def _get_last_updated_file(src_file):
if not os.path.exists(src_file): if not os.path.exists(src_file):
return None return None
try: try:
last_updated_t = subprocess.check_output( last_updated_t = (
[ subprocess.check_output(
'git', 'log', '-n1', '--format=%ad', [
'--date=format:%Y-%m-%d %H:%M:%S', 'git',
'--', src_file, 'log',
] '-n1',
).decode('utf-8').strip() '--format=%ad',
'--date=format:%Y-%m-%d %H:%M:%S',
'--',
src_file,
]
)
.decode('utf-8')
.strip()
)
# NOTE: we catch any exception here (instead of # NOTE: we catch any exception here (instead of
# subprocess.CalledProcessError and OSError) because some projects (eg. # subprocess.CalledProcessError and OSError) because some projects (eg.
# neutron) do import eventlet in docs/source/conf.py which will patch # neutron) do import eventlet in docs/source/conf.py which will patch
@ -45,17 +53,22 @@ def _get_last_updated_file(src_file):
except Exception as err: except Exception as err:
LOG.info( LOG.info(
'[openstackdocstheme] Could not get modification time of %s: %s', '[openstackdocstheme] Could not get modification time of %s: %s',
src_file, err) src_file,
err,
)
else: else:
if last_updated_t: if last_updated_t:
try: try:
return datetime.datetime.strptime(last_updated_t, return datetime.datetime.strptime(
'%Y-%m-%d %H:%M:%S') last_updated_t, '%Y-%m-%d %H:%M:%S'
)
except ValueError: except ValueError:
LOG.info( LOG.info(
'[openstackdocstheme] ' '[openstackdocstheme] '
'Could not parse modification time of %s: %r', 'Could not parse modification time of %s: %r',
src_file, last_updated_t) src_file,
last_updated_t,
)
return None return None
@ -67,7 +80,7 @@ def _get_last_updated(app, pagename):
# Strip the prefix from the filename so the git command recognizes # Strip the prefix from the filename so the git command recognizes
# the file as part of the current repository. # the file as part of the current repository.
src_file = full_src_file[len(str(app.builder.env.srcdir)):].lstrip('/') src_file = full_src_file[len(str(app.builder.env.srcdir)) :].lstrip('/')
candidates.append(src_file) candidates.append(src_file)
if not os.path.exists(src_file): if not os.path.exists(src_file):
@ -82,7 +95,9 @@ def _get_last_updated(app, pagename):
if last_updated: if last_updated:
LOG.debug( LOG.debug(
'[openstackdocstheme] Last updated for %s is %s', '[openstackdocstheme] Last updated for %s is %s',
pagename, last_updated) pagename,
last_updated,
)
return last_updated return last_updated
if pagename not in ('genindex', 'search'): if pagename not in ('genindex', 'search'):

6
pyproject.toml Normal file
View File

@ -0,0 +1,6 @@
[tool.ruff]
line-length = 79
[tool.ruff.format]
quote-style = "preserve"
docstring-code-format = true

View File

@ -52,8 +52,8 @@ source_suffix = '.rst'
master_doc = 'index' master_doc = 'index'
# General information about the project. # General information about the project.
project = u'OpenStackdocstheme Release Notes' project = 'OpenStackdocstheme Release Notes'
copyright = u'2017, OpenStack Documentation team' copyright = '2017, OpenStack Documentation team'
# Release notes are version independent. # Release notes are version independent.
# The full version, including alpha/beta/rc tags. # The full version, including alpha/beta/rc tags.
@ -193,10 +193,8 @@ htmlhelp_basename = 'OpenStackDocsThemeReleaseNotesdoc'
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': '',
} }
@ -205,9 +203,13 @@ latex_elements = {
# (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', 'OpenStackdocstheme-ReleaseNotes.tex', (
u'OpenStackdocstheme Release Notes Documentation', 'index',
u'Documentation Team', 'manual'), 'OpenStackdocstheme-ReleaseNotes.tex',
'OpenStackdocstheme Release Notes Documentation',
'Documentation Team',
'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
@ -236,9 +238,13 @@ latex_documents = [
# One entry per manual page. List of tuples # One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section). # (source start file, name, description, authors, manual section).
man_pages = [ man_pages = [
('index', 'openstackdocstheme-releasenotes', (
u'OpenStackdocstheme Release Notes Documentation', 'index',
[u'Documentation team'], 1) 'openstackdocstheme-releasenotes',
'OpenStackdocstheme Release Notes Documentation',
['Documentation team'],
1,
)
] ]
# If true, show URL addresses after external links. # If true, show URL addresses after external links.
@ -251,11 +257,15 @@ 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', 'OpenStackDocsTheme-ReleaseNotes', (
u'OpenStackDocsTheme Release Notes Documentation', 'index',
u'Documentation Team', 'OpenStackDocsTheme-ReleaseNotes', 'OpenStackDocsTheme-ReleaseNotes',
'One line description of project.', 'OpenStackDocsTheme Release Notes Documentation',
'Miscellaneous'), 'Documentation Team',
'OpenStackDocsTheme-ReleaseNotes',
'One line description of project.',
'Miscellaneous',
),
] ]
# Documents to append as an appendix to all manuals. # Documents to append as an appendix to all manuals.

View File

@ -16,6 +16,4 @@
# THIS FILE IS MANAGED BY THE GLOBAL REQUIREMENTS REPO - DO NOT EDIT # THIS FILE IS MANAGED BY THE GLOBAL REQUIREMENTS REPO - DO NOT EDIT
import setuptools import setuptools
setuptools.setup( setuptools.setup(setup_requires=['pbr>=2.0.0'], pbr=True)
setup_requires=['pbr>=2.0.0'],
pbr=True)

View File

@ -86,4 +86,7 @@ commands = bindep test
[flake8] [flake8]
exclude=.venv,.git,.tox,dist,doc,api-ref,*lib/python*,*egg,tools exclude=.venv,.git,.tox,dist,doc,api-ref,*lib/python*,*egg,tools
show-source = True show-source = True
enable-extensions = H203,H106 # We only enable the hacking (H) checks
select = H
# H304 We're okay with relative imports
ignore = H304