pax_global_header 0000666 0000000 0000000 00000000064 14574374461 0014531 g ustar 00root root 0000000 0000000 52 comment=a7cad48b6eddf6a461e3fae91f231dc3e3f2a88f
autoprogram-0.1.9/ 0000775 0000000 0000000 00000000000 14574374461 0014100 5 ustar 00root root 0000000 0000000 autoprogram-0.1.9/.github/ 0000775 0000000 0000000 00000000000 14574374461 0015440 5 ustar 00root root 0000000 0000000 autoprogram-0.1.9/.github/workflows/ 0000775 0000000 0000000 00000000000 14574374461 0017475 5 ustar 00root root 0000000 0000000 autoprogram-0.1.9/.github/workflows/build.yml 0000664 0000000 0000000 00000003724 14574374461 0021325 0 ustar 00root root 0000000 0000000 name: Build and Test
on:
release:
types: [ published ]
push:
branches: [ master ]
pull_request:
branches: [ master ]
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.8", "3.9", "3.10", "3.11", "3.12"]
steps:
- uses: actions/checkout@v2
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v2
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
python -m pip install --upgrade pip
python -m pip install setuptools tox
# NOTE(lb): By creating a sdist and then testing/working with that, we ensure
# its completeness.
- name: Move to sdist
run: |
python setup.py sdist
mkdir tmp
mv dist/*.tar.gz tmp/
cd tmp/
tar xvf *.tar.gz
for f in *; do
if [[ -d ${f} ]]; then
printf "Moving %s to %s\n" "${f}" "$PWD/sdist"
mv "${f}" sdist
break
fi
done
- name: Build
run: |
pwd
pip install wheel
python setup.py sdist bdist_wheel
working-directory: ${{ github.workspace }}/tmp/sdist
- name: Tox
run: |
tox --skip-missing-interpreters
working-directory: ${{ github.workspace }}/tmp/sdist
- name: Build documentation
run: |
pip install -r doc/rtd-requires.txt
cd doc
make html
working-directory: ${{ github.workspace }}/tmp/sdist
- name: Install wheel
run: |
pip install dist/*.whl
working-directory: ${{ github.workspace }}/tmp/sdist
- name: Publish package
if: github.event_name == 'release' && startsWith(github.ref, 'refs/tags') && matrix.python-version == 3.12
uses: pypa/gh-action-pypi-publish@v1.4.2
with:
user: __token__
password: ${{ secrets.PYPI_API_TOKEN }}
packages_dir: ${{ github.workspace }}/tmp/sdist/dist
autoprogram-0.1.9/.gitignore 0000664 0000000 0000000 00000000127 14574374461 0016070 0 ustar 00root root 0000000 0000000 *.egg-info/
mypy_cache/
*.pyc
.*.swp
.cache/
.tox/
__pycache__/
build
dist
doc/_build/
autoprogram-0.1.9/.pylintrc 0000664 0000000 0000000 00000002155 14574374461 0015750 0 ustar 00root root 0000000 0000000 [MASTER]
ignore=.git
jobs=0
suggestion-mode=yes
[MESSAGES CONTROL]
disable=all
enable=assign-to-new-keyword,
bad-format-character,
bad-format-string-key,
bad-open-mode,
bad-string-format-type,
consider-using-get,
consider-using-join,
empty-docstring,
function-redefined,
not-in-loop,
redefined-builtin,
return-in-init,
too-few-format-args,
too-many-format-args,
truncated-format-string,
unnecessary-comprehension,
unused-argument,
unreachable,
unused-format-string-argument,
unused-format-string-key,
unused-import,
unused-variable,
using-constant-test
[REPORTS]
output-format=text
reports=no
score=no
[BASIC]
argument-naming-style=snake_case
attr-naming-style=snake_case
class-naming-style=PascalCase
const-naming-style=UPPER_CASE
function-naming-style=snake_case
include-naming-hint=yes
inlinevar-naming-style=snake_case
method-naming-style=snake_case
module-naming-style=snake_case
variable-naming-style=snake_case
[VARIABLES]
redefining-builtins-modules=builtins,io
autoprogram-0.1.9/LICENSE 0000664 0000000 0000000 00000003031 14574374461 0015102 0 ustar 00root root 0000000 0000000 Copyright (c) 2014–2018 Hong Minhee
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the sphinxcontrib-autoprogram project.
autoprogram-0.1.9/MANIFEST.in 0000664 0000000 0000000 00000000121 14574374461 0015630 0 ustar 00root root 0000000 0000000 include README
include LICENSE
include CHANGES.*
tox.ini
recursive-include doc *
autoprogram-0.1.9/README.rst 0000664 0000000 0000000 00000002002 14574374461 0015561 0 ustar 00root root 0000000 0000000 ``sphinxcontrib.autoprogram``
=============================
.. image:: https://badge.fury.io/py/sphinxcontrib-autoprogram.svg
:target: https://pypi.org/project/sphinxcontrib-autoprogram/
:alt: Latest PyPI version
.. image:: https://readthedocs.org/projects/sphinxcontrib-autoprogram/badge/
:target: https://sphinxcontrib-autoprogram.readthedocs.io/
:alt: Documentation Status
.. image:: https://github.com/sphinx-contrib/autoprogram/workflows/Build%20and%20Test/badge.svg?branch=master
:target: https://github.com/sphinx-contrib/autoprogram/actions
:alt: Build Status
This contrib extension, ``sphinxcontrib.autoprogram``, provides an automated
way to document CLI programs. It scans ``argparse.ArgumentParser`` object,
and then expands it into a set of ``.. program::`` and ``.. option::``
directives.
Install using ``pip``:
.. code-block:: console
$ pip install sphinxcontrib-autoprogram
You can find the documentation from the following URL:
https://sphinxcontrib-autoprogram.readthedocs.io/
autoprogram-0.1.9/doc/ 0000775 0000000 0000000 00000000000 14574374461 0014645 5 ustar 00root root 0000000 0000000 autoprogram-0.1.9/doc/Makefile 0000664 0000000 0000000 00000015266 14574374461 0016317 0 ustar 00root root 0000000 0000000 # Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = _build
# User-friendly check for sphinx-build
ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)
$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/)
endif
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
help:
@echo "Please use \`make ' where is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " xml to make Docutils-native XML files"
@echo " pseudoxml to make pseudoxml-XML files for display purposes"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/sphinxcontrib-autoprogram.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/sphinxcontrib-autoprogram.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/sphinxcontrib-autoprogram"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/sphinxcontrib-autoprogram"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
latexpdfja:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through platex and dvipdfmx..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
xml:
$(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
@echo
@echo "Build finished. The XML files are in $(BUILDDIR)/xml."
pseudoxml:
$(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
@echo
@echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
autoprogram-0.1.9/doc/changelog.rst 0000664 0000000 0000000 00000005343 14574374461 0017333 0 ustar 00root root 0000000 0000000 Changelog
=========
Version 0.1.9
-------------
Released on March 13, 2024.
- Test against Python 3.12.
- Drop support for Python 3.7.
Version 0.1.8
-------------
Released on February 11, 2023.
- Test against Python 3.10, 3.11.
Version 0.1.7
-------------
Released on February 10, 2021.
- Publish to PyPI via Github Actions.
Version 0.1.6
-------------
Released on February 10, 2021.
- Dropped support for Python 2 and Pypy
- Declare this extension safe for parallel reading
- Migrate to Github Actions for CI [:issue:`28`, :pull:`32` by Langston Barrett]
- Test against recent versions of Sphinx [:issue:`33`, :pull:`32` by Langston Barrett]
- Format source code with Black [:issue:`30`, :pull:`32` by Langston Barrett]
- Add documentation to the ``sdist`` [:issue:`26`, :pull:`32` by Langston Barrett]
- Fixed unwanted ``
`` tags in multi-line command descriptions that
are indented to match surrounding code. [:pull:`21` by dgw]
Version 0.1.5
-------------
Released on May 15, 2018.
- New ``:groups:`` option to render argument groups. [by Lukas Atkinson]
Version 0.1.4
-------------
Released on February 27, 2018.
- Fixed a :rst:dir`.. autoprogram::` bug that raises :exc:`AttributeError`
during build without ``:no_usage_codeblock:`` option on Python 2.
[:bbissue:`168`, :bbissue:`169`]
- Fixed an issue with Sphinx 1.7 which removed ``sphinx.util.compat``.
[:issue:`1`, :pull:`2` by Zach Riggle]
Version 0.1.3
-------------
Released on October 7, 2016.
- Fixed a bug that descriptions with :class:`~argparse.RawTextHelpFormatter`
had been incorrectly formatted. [:bbpull:`123` by Aaron Meurer]
- Fixed crash when metavars is a tuple (i.e. for ``nargs > 1``).
[:bbpull:`112` by Alex Honeywell]
- Fixed usage string for subcommands (subcommands were previously showing
the top-level command usage). [:bbpull:`112` by Alex Honeywell]
- Added :ref:`new options ` to :rst:dir:`.. autoprogram::`
directive: [:bbpull:`112` by Alex Honeywell]
- ``maxdepth``
- ``no_usage_codeblock``
- ``start_command``
- ``strip_usage``
- Fixed suppressed arguments (using :const:`argparse.SUPPRESS` flag)
to become ignored. [:bbissue:`166`]
Version 0.1.2
-------------
Released on August 18, 2015.
- Fixed crash with empty fields. [:bbissue:`110`]
- Fixed :exc:`ImportError` with non-module Python scripts (i.e. files not
ending with :file:`.py`). [:bbpull:`101` by Matteo Bachetti]
Version 0.1.1
-------------
Released on April 22, 2014.
- Omit metavars of ``store_const``/``store_true``/``store_false`` options.
- Sort subcommands in alphabetical order if Python 2.6 which doesn't have
:class:`collections.OrderedDict`.
Version 0.1.0
-------------
Released on March 2, 2014. The first release.
autoprogram-0.1.9/doc/cli.py 0000664 0000000 0000000 00000001231 14574374461 0015763 0 ustar 00root root 0000000 0000000 import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='An integer for the accumulator.')
parser.add_argument('-i', '--identity', type=int, default=0,
help='the default result for no arguments '
'(default: 0)')
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='Sum the integers (default: find the max).')
if __name__ == '__main__':
args = parser.parse_args()
print(args.accumulate(args.integers))
autoprogram-0.1.9/doc/cli_with_groups.py 0000664 0000000 0000000 00000001257 14574374461 0020425 0 ustar 00root root 0000000 0000000 import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='An integer for the accumulator.')
calculator_opts = parser.add_argument_group('Calculator Options')
calculator_opts.add_argument(
'-i', '--identity', type=int, default=0,
help='the default result for no arguments ' '(default: 0)')
calculator_opts.add_argument(
'--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='Sum the integers (default: find the max).')
if __name__ == '__main__':
args = parser.parse_args()
print(args.accumulate(args.integers))
autoprogram-0.1.9/doc/conf.py 0000664 0000000 0000000 00000022524 14574374461 0016151 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# sphinxcontrib-autoprogram documentation build configuration file, created by
# sphinx-quickstart on Sun Mar 2 02:39:38 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import ast
import sys
import os.path
# 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('..'))
sys.path.insert(1, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
needs_sphinx = '1.2'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.intersphinx',
'sphinx.ext.extlinks',
'sphinxcontrib.autoprogram',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'sphinxcontrib-autoprogram'
copyright = u'2014, Hong Minhee'
# 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.
with open(os.path.join('..', 'setup.py')) as _f:
_setup_ast = ast.parse(_f.read(), _f.name)
del _f
# The full version, including alpha/beta/rc tags.
release = next(
node.value.s
for node in ast.walk(_setup_ast)
if (isinstance(node, ast.Assign) and len(node.targets) == 1 and
isinstance(node.targets[0], ast.Name) and
node.targets[0].id == 'version' and isinstance(node.value, ast.Str))
)
# The short X.Y version.
version = release[:release.rfind('.')]
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# 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
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
html_theme_options = {'nosidebar': True}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# " v documentation".
html_title = '{0} {1}'.format(project, release)
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# 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
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'sphinxcontrib-autoprogramdoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
('index', 'sphinxcontrib-autoprogram.tex', u'sphinxcontrib-autoprogram Documentation',
u'Hong Minhee', 'manual'),
]
# 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
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'sphinxcontrib-autoprogram', u'sphinxcontrib-autoprogram Documentation',
[u'Hong Minhee'], 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 = [
('index', 'sphinxcontrib-autoprogram', u'sphinxcontrib-autoprogram Documentation',
u'Hong Minhee', 'sphinxcontrib-autoprogram', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {
'python': ('http://docs.python.org/', None),
'sphinx': ('http://sphinx-doc.org/', None)
}
extlinks = {
'pull': (
'https://github.com/sphinx-contrib/autoprogram/pull/%s',
'#%s'
),
'issue': (
'https://github.com/sphinx-contrib/autoprogram/issues/%s',
'#%s'
),
'bbpull': (
'https://bitbucket.org/birkenfeld/sphinx-contrib/pull-request/%s/',
'Bitbucket PR #%s',
),
'bbissue': (
'https://bitbucket.org/birkenfeld/sphinx-contrib/issue/%s/',
'Bitbucket issue #%s',
),
}
autoprogram-0.1.9/doc/index.rst 0000664 0000000 0000000 00000011531 14574374461 0016507 0 ustar 00root root 0000000 0000000 .. sphinxcontrib-autoprogram documentation master file, created by
sphinx-quickstart on Sun Mar 2 02:39:38 2014.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
.. module:: sphinxcontrib.autoprogram
:mod:`sphinxcontrib.autoprogram` --- Documenting CLI programs
=============================================================
.. image:: https://badge.fury.io/py/sphinxcontrib-autoprogram.svg
:target: https://pypi.org/project/sphinxcontrib-autoprogram/
:alt: Latest PyPI version
.. image:: https://readthedocs.org/projects/sphinxcontrib-autoprogram/badge/
:target: https://sphinxcontrib-autoprogram.readthedocs.io/
:alt: Documentation Status
.. image:: https://github.com/sphinx-contrib/autoprogram/workflows/Build%20and%20Test/badge.svg?branch=master
:target: https://github.com/sphinx-contrib/autoprogram/actions
:alt: Build Status
This contrib extension, :mod:`sphinxcontrib.autoprogram`, provides an automated
way to document CLI programs. It scans :class:`argparse.ArgumentParser`
object, and then expands it into a set of :rst:dir:`.. program::` and
:rst:dir:`.. option::` directives.
In order to use it, add :mod:`sphinxcontrib.autoprogram` into
:data:`extensions` list of your Sphinx configuration file (:file:`conf.py`)::
extensions = ['sphinxcontrib.autoprogram']
.. seealso::
Module :mod:`argparse`
This extension assumes a program to document is made using
:mod:`argparse` module which is a part of the Python standard library.
:rst:dir:`.. autoprogram::` directive
-------------------------------------
Its only and simple way to use is :rst:dir:`.. autoprogram::` directive.
It's similar to :mod:`sphinx.ext.autodoc` extension's
:rst:dir:`.. automodule::` and other directives.
For example, given the following Python CLI program (say it's :file:`cli.py`):
.. include:: cli.py
:code:
In order to document the above program:
.. code-block:: rst
.. autoprogram:: cli:parser
:prog: cli.py
That's it. It will be rendered as:
.. autoprogram:: cli:parser
:prog: cli.py
If there are subcommands (subparsers), they are rendered to subsections.
For example, given the following Python CLI program (say it's
:file:`subcmds.py`):
.. include:: subcmds.py
:code:
.. code-block:: rst
.. autoprogram:: subcmds:parser
:prog: subcmds.py
The above reStructuredText will render:
.. autoprogram:: subcmds:parser
:prog: subcmds.py
If there are argument groups, they can optionally be rendered as subsections,
just like subcommands.
For example:
.. include:: cli_with_groups.py
:code:
.. code-block:: rst
.. autoprogram:: cli_with_groups:parser
:prog: cli_with_groups.py
:groups:
The above reStructuredText Text will render:
.. autoprogram:: cli_with_groups:parser
:prog: cli_with_groups.py
:groups:
.. rst:directive:: .. autoprogram:: module:parser
It takes an import name of the parser object. For example, if ``xyz``
variable in ``abcd.efgh`` module refers an :class:`argparse.ArgumentParser`
object:
.. code-block:: rst
.. autoprogram:: abcd.efgh:xyz
The import name also can evaluate other any Python expressions.
For example, if ``get_parser()`` function in ``abcd.efgh`` module creates
an :class:`argparse.ArgumentParser` and returns it:
.. code-block:: rst
.. autoprogram:: abcd.efgh:get_parser()
It also optionally takes an option named ``prog``. If it's not present
``prog`` option uses :class:`~argparse.ArgumentParser` object's
prog_ value.
.. _prog: http://docs.python.org/library/argparse.html#prog
.. _autoprogram-options:
Additional Options for :rst:dir:`.. autoprogram::`
--------------------------------------------------
``:groups:``
Render argument groups as subsections.
.. versionadded:: 0.1.5
``:maxdepth: ##``
Only show subcommands to a depth of ``##``.
.. versionadded:: 0.1.3
``:no_usage_codeblock:``
Don't put the usage text in a :rst:dir:`.. codeblock:: console` directive.
.. versionadded:: 0.1.3
``:start_command: subcommand``
Render document for the given subcommand. ``subcommand`` can be a space
separated list to render a sub-sub-...-command.
.. versionadded:: 0.1.3
``:strip_usage:``
Removes all but the last word in the usage string before the first option,
replaces it with '...', and removes an amount of whitespace to realign
subsequent lines.
.. versionadded:: 0.1.3
Author and license
------------------
The :mod:`sphinxcontrib.autoprogram` is written by `Hong Minhee`__ and
distributed under BSD license.
The source code is maintained under the `GitHub repository`__:
.. sourcecode:: console
$ git clone git://github.com/sphinx-contrib/autoprogram.git
__ https://hongminhee.org/
__ https://github.com/sphinx-contrib/autoprogram
.. include:: changelog.rst
autoprogram-0.1.9/doc/make.bat 0000664 0000000 0000000 00000015123 14574374461 0016254 0 ustar 00root root 0000000 0000000 @ECHO OFF
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set BUILDDIR=_build
set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% .
set I18NSPHINXOPTS=%SPHINXOPTS% .
if NOT "%PAPER%" == "" (
set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%
)
if "%1" == "" goto help
if "%1" == "help" (
:help
echo.Please use `make ^` where ^ is one of
echo. html to make standalone HTML files
echo. dirhtml to make HTML files named index.html in directories
echo. singlehtml to make a single large HTML file
echo. pickle to make pickle files
echo. json to make JSON files
echo. htmlhelp to make HTML files and a HTML help project
echo. qthelp to make HTML files and a qthelp project
echo. devhelp to make HTML files and a Devhelp project
echo. epub to make an epub
echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter
echo. text to make text files
echo. man to make manual pages
echo. texinfo to make Texinfo files
echo. gettext to make PO message catalogs
echo. changes to make an overview over all changed/added/deprecated items
echo. xml to make Docutils-native XML files
echo. pseudoxml to make pseudoxml-XML files for display purposes
echo. linkcheck to check all external links for integrity
echo. doctest to run all doctests embedded in the documentation if enabled
goto end
)
if "%1" == "clean" (
for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
del /q /s %BUILDDIR%\*
goto end
)
%SPHINXBUILD% 2> nul
if errorlevel 9009 (
echo.
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
echo.installed, then set the SPHINXBUILD environment variable to point
echo.to the full path of the 'sphinx-build' executable. Alternatively you
echo.may add the Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.http://sphinx-doc.org/
exit /b 1
)
if "%1" == "html" (
%SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/html.
goto end
)
if "%1" == "dirhtml" (
%SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
goto end
)
if "%1" == "singlehtml" (
%SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.
goto end
)
if "%1" == "pickle" (
%SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the pickle files.
goto end
)
if "%1" == "json" (
%SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the JSON files.
goto end
)
if "%1" == "htmlhelp" (
%SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run HTML Help Workshop with the ^
.hhp project file in %BUILDDIR%/htmlhelp.
goto end
)
if "%1" == "qthelp" (
%SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run "qcollectiongenerator" with the ^
.qhcp project file in %BUILDDIR%/qthelp, like this:
echo.^> qcollectiongenerator %BUILDDIR%\qthelp\sphinxcontrib-autoprogram.qhcp
echo.To view the help file:
echo.^> assistant -collectionFile %BUILDDIR%\qthelp\sphinxcontrib-autoprogram.ghc
goto end
)
if "%1" == "devhelp" (
%SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished.
goto end
)
if "%1" == "epub" (
%SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The epub file is in %BUILDDIR%/epub.
goto end
)
if "%1" == "latex" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
if errorlevel 1 exit /b 1
echo.
echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "latexpdf" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
cd %BUILDDIR%/latex
make all-pdf
cd %BUILDDIR%/..
echo.
echo.Build finished; the PDF files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "latexpdfja" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
cd %BUILDDIR%/latex
make all-pdf-ja
cd %BUILDDIR%/..
echo.
echo.Build finished; the PDF files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "text" (
%SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The text files are in %BUILDDIR%/text.
goto end
)
if "%1" == "man" (
%SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The manual pages are in %BUILDDIR%/man.
goto end
)
if "%1" == "texinfo" (
%SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo.
goto end
)
if "%1" == "gettext" (
%SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The message catalogs are in %BUILDDIR%/locale.
goto end
)
if "%1" == "changes" (
%SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
if errorlevel 1 exit /b 1
echo.
echo.The overview file is in %BUILDDIR%/changes.
goto end
)
if "%1" == "linkcheck" (
%SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
if errorlevel 1 exit /b 1
echo.
echo.Link check complete; look for any errors in the above output ^
or in %BUILDDIR%/linkcheck/output.txt.
goto end
)
if "%1" == "doctest" (
%SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
if errorlevel 1 exit /b 1
echo.
echo.Testing of doctests in the sources finished, look at the ^
results in %BUILDDIR%/doctest/output.txt.
goto end
)
if "%1" == "xml" (
%SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The XML files are in %BUILDDIR%/xml.
goto end
)
if "%1" == "pseudoxml" (
%SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml.
goto end
)
:end
autoprogram-0.1.9/doc/rtd-requires.txt 0000664 0000000 0000000 00000000101 14574374461 0020024 0 ustar 00root root 0000000 0000000 -e .
Sphinx[websupport] >= 1.7
sphinxcontrib-websupport >= 1.0.1
autoprogram-0.1.9/doc/subcmds.py 0000664 0000000 0000000 00000001322 14574374461 0016655 0 ustar 00root root 0000000 0000000 import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
subparsers = parser.add_subparsers()
max_parser = subparsers.add_parser('max', description='Find the max.')
max_parser.set_defaults(accumulate=max)
max_parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='An integer for the accumulator.')
sum_parser = subparsers.add_parser('sum', description='Sum the integers.')
sum_parser.set_defaults(accumulate=sum)
sum_parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='An integer for the accumulator.')
if __name__ == '__main__':
args = parser.parse_args()
print(args.accumulate(args.integers))
autoprogram-0.1.9/mypy.ini 0000664 0000000 0000000 00000000437 14574374461 0015603 0 ustar 00root root 0000000 0000000 [mypy]
# TODO: Enable these
# disallow_any_generics = True
# disallow_incomplete_defs = True
# disallow_untyped_defs = True
show_error_codes = True
ignore_missing_imports = True
no_implicit_optional = True
warn_redundant_casts = True
warn_unused_configs = True
warn_unused_ignores = True autoprogram-0.1.9/setup.cfg 0000664 0000000 0000000 00000000034 14574374461 0015716 0 ustar 00root root 0000000 0000000 [bdist_wheel]
universal = 1
autoprogram-0.1.9/setup.py 0000664 0000000 0000000 00000003400 14574374461 0015607 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
from __future__ import with_statement
import sys
from setuptools import setup, find_packages
# Do not change the variable name. It's parsed by doc/conf.py script.
version = '0.1.9'
requires = ['Sphinx >= 1.2']
def readme():
with open('README.rst') as f:
return f.read()
setup(
name='sphinxcontrib-autoprogram',
version=version,
url='https://github.com/sphinx-contrib/autoprogram',
license='2-Clause BSD',
author='Hong Minhee',
author_email='\x68\x6f\x6e\x67.minhee' '@' '\x67\x6d\x61\x69\x6c.com',
description='Documenting CLI programs',
long_description=readme(),
zip_safe=False,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Environment :: Web Environment',
'Framework :: Sphinx :: Extension',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
'Programming Language :: Python :: 3.11',
'Programming Language :: Python :: 3.12',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: Stackless',
'Topic :: Documentation',
'Topic :: Software Development :: Documentation',
'Topic :: Utilities'
],
python_requires='>=3.8',
platforms='any',
packages=find_packages(),
namespace_packages=['sphinxcontrib'],
include_package_data=True,
install_requires=requires,
test_suite='sphinxcontrib.autoprogram.suite'
)
autoprogram-0.1.9/sphinxcontrib/ 0000775 0000000 0000000 00000000000 14574374461 0016772 5 ustar 00root root 0000000 0000000 autoprogram-0.1.9/sphinxcontrib/__init__.py 0000664 0000000 0000000 00000000555 14574374461 0021110 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
"""
sphinxcontrib
~~~~~~~~~~~~~
This package is a namespace package that contains all extensions
distributed in the ``sphinx-contrib`` distribution.
:copyright: Copyright 2007-2014 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
__import__("pkg_resources").declare_namespace(__name__)
autoprogram-0.1.9/sphinxcontrib/autoprogram.py 0000664 0000000 0000000 00000046671 14574374461 0021722 0 ustar 00root root 0000000 0000000 """
sphinxcontrib.autoprogram
~~~~~~~~~~~~~~~~~~~~~~~~~
Documenting CLI programs.
:copyright: Copyright 2014 by Hong Minhee
:license: BSD, see LICENSE for details.
"""
from __future__ import annotations
# pylint: disable=protected-access,missing-docstring
import argparse
import builtins
import collections
import inspect
import os
import re
import sys
import tempfile
from functools import reduce
from typing import Any, Dict, Iterable, List, Optional, Tuple
import unittest
from unittest import mock
from docutils import nodes
from docutils.parsers.rst import Directive
from docutils.parsers.rst.directives import unchanged
from docutils.statemachine import StringList, ViewList
from sphinx.domains import std
from sphinx.util.nodes import nested_parse_with_titles
__all__ = (
"AutoprogramDirective",
"AutoprogramDirectiveTestCase",
"ScannerTestCase",
"import_object",
"scan_programs",
"setup",
"suite",
)
def get_subparser_action(
parser: argparse.ArgumentParser,
) -> Optional[argparse._SubParsersAction]:
neg1_action = parser._actions[-1]
if isinstance(neg1_action, argparse._SubParsersAction):
return neg1_action
for a in parser._actions:
if isinstance(a, argparse._SubParsersAction):
return a
return None
def scan_programs(
parser: argparse.ArgumentParser,
command=[],
maxdepth: int = 0,
depth: int = 0,
groups: bool = False,
):
if maxdepth and depth >= maxdepth:
return
if groups:
yield command, [], parser
for group in parser._action_groups:
options = list(scan_options(group._group_actions))
if options:
yield command, options, group
else:
options = list(scan_options(parser._actions))
yield command, options, parser
if parser._subparsers:
choices: Iterable[Tuple[Any, Any]] = ()
subp_action = get_subparser_action(parser)
if subp_action:
choices = subp_action.choices.items()
if not (
hasattr(collections, "OrderedDict")
and isinstance(choices, collections.OrderedDict)
):
choices = sorted(choices, key=lambda pair: pair[0])
for cmd, sub in choices:
if isinstance(sub, argparse.ArgumentParser):
for program in scan_programs(sub, command + [cmd], maxdepth, depth + 1):
yield program
def scan_options(actions):
for arg in actions:
if not (arg.option_strings or isinstance(arg, argparse._SubParsersAction)):
yield format_positional_argument(arg)
for arg in actions:
if arg.option_strings and arg.help is not argparse.SUPPRESS:
yield format_option(arg)
def format_positional_argument(arg) -> Tuple[List[str], str]:
desc = (arg.help or "") % {"default": arg.default}
name = (arg.metavar or arg.dest).lower()
return [name], desc
def format_option(arg) -> Tuple[List[str], str]:
desc = (arg.help or "") % {"default": arg.default}
if not isinstance(arg, (argparse._StoreAction, argparse._AppendAction)):
names = list(arg.option_strings)
return names, desc
if arg.choices is not None:
value = "{{{0}}}".format(",".join(str(c) for c in arg.choices))
else:
metavar = arg.metavar or arg.dest
if not isinstance(metavar, tuple):
metavar = (metavar,)
value = "<{0}>".format("> <".join(metavar).lower())
names = [
"{0} {1}".format(option_string, value) for option_string in arg.option_strings
]
return names, desc
def import_object(import_name: str):
module_name, expr = import_name.split(":", 1)
try:
mod = __import__(module_name)
except ImportError:
# This happens if the file is a script with no .py extension. Here we
# trick autoprogram to load a module in memory with the contents of
# the script, if there is a script named module_name. Otherwise, raise
# an ImportError as it did before.
import glob
import os
import sys
import types
for p in sys.path:
f = glob.glob(os.path.join(p, module_name))
if len(f) > 0:
with open(f[0]) as fobj:
codestring = fobj.read()
foo = types.ModuleType("foo")
exec(codestring, foo.__dict__)
sys.modules["foo"] = foo
mod = __import__("foo")
break
else:
raise
mod = reduce(getattr, module_name.split(".")[1:], mod)
globals_: Dict[str, Any] = builtins # type: ignore[assignment]
if not isinstance(globals_, dict):
globals_ = globals_.__dict__
return eval(expr, globals_, mod.__dict__)
class AutoprogramDirective(Directive):
has_content = False
required_arguments = 1
option_spec = {
"prog": unchanged,
"maxdepth": unchanged,
"start_command": unchanged,
"strip_usage": unchanged,
"no_usage_codeblock": unchanged,
"groups": unchanged,
}
def make_rst(self):
(import_name,) = self.arguments
parser = import_object(import_name or "__undefined__")
prog = self.options.get("prog")
if prog:
original_prog = parser.prog
parser.prog = prog
start_command = self.options.get("start_command", "").split(" ")
strip_usage = "strip_usage" in self.options
usage_codeblock = "no_usage_codeblock" not in self.options
maxdepth = int(self.options.get("maxdepth", 0))
groups = "groups" in self.options
if start_command[0] == "":
start_command.pop(0)
if start_command:
def get_start_cmd_parser(p):
looking_for = start_command.pop(0)
action = get_subparser_action(p)
if not action:
raise ValueError("No actions for command " + looking_for)
subp = action.choices[looking_for]
if start_command:
return get_start_cmd_parser(subp)
return subp
parser = get_start_cmd_parser(parser)
if prog and parser.prog.startswith(original_prog):
parser.prog = parser.prog.replace(original_prog, prog, 1)
for commands, options, group_or_parser in scan_programs(
parser, maxdepth=maxdepth, groups=groups
):
if isinstance(group_or_parser, argparse._ArgumentGroup):
title = group_or_parser.title
description = group_or_parser.description
usage = None
epilog = None
is_subgroup = True
is_program = False
else:
cmd_parser = group_or_parser
if prog and cmd_parser.prog.startswith(original_prog):
cmd_parser.prog = cmd_parser.prog.replace(original_prog, prog, 1)
title = cmd_parser.prog.rstrip()
description = cmd_parser.description
usage = cmd_parser.format_usage()
epilog = cmd_parser.epilog
is_subgroup = bool(commands)
is_program = True
for line in render_rst(
title,
options,
is_program=is_program,
is_subgroup=is_subgroup,
description=description,
usage=usage,
usage_strip=strip_usage,
usage_codeblock=usage_codeblock,
epilog=epilog,
):
yield line
def run(self):
node = nodes.section()
node.document = self.state.document
result = ViewList()
for line in self.make_rst():
result.append(line, "")
nested_parse_with_titles(self.state, result, node)
return node.children
def render_rst(
title: str,
options,
is_program: bool,
is_subgroup: bool,
description: Optional[str],
usage: str,
usage_strip: bool,
usage_codeblock: bool,
epilog: Optional[str],
) -> Iterable[str]:
if usage_strip:
to_strip = title.rsplit(" ", 1)[0]
len_to_strip = len(to_strip) - 4
usage_lines = usage.splitlines()
usage = os.linesep.join(
[
usage_lines[0].replace(to_strip, "..."),
]
+ [line[len_to_strip:] for line in usage_lines[1:]]
)
yield ""
if is_program:
yield ".. program:: " + title
yield ""
yield title
yield ("!" if is_subgroup else "?") * len(title)
yield ""
for line in inspect.cleandoc(description or "").splitlines():
yield line
yield ""
if usage is None:
pass
elif usage_codeblock:
yield ".. code-block:: console"
yield ""
for usage_line in usage.splitlines():
yield " " + usage_line
else:
yield usage
yield ""
for option_strings, help_ in options:
yield ".. option:: {0}".format(", ".join(option_strings))
yield ""
yield " " + help_.replace("\n", " \n")
yield ""
for line in (epilog or "").splitlines():
yield line or ""
def patch_option_role_to_allow_argument_form() -> None:
"""Before Sphinx 1.2.2, :rst:dir:`.. option::` directive hadn't
allowed to not start with a dash or slash, so it hadn't been possible
to represent positional arguments (not options).
https://bitbucket.org/birkenfeld/sphinx/issue/1357/
It monkeypatches the :rst:dir:`.. option::` directive's behavior.
"""
std.option_desc_re = re.compile(r"((?:/|-|--)?[-_a-zA-Z0-9]+)(\s*.*)")
def setup(app) -> Dict[str, bool]:
app.add_directive("autoprogram", AutoprogramDirective)
patch_option_role_to_allow_argument_form()
return {
"parallel_read_safe": True,
"parallel_write_safe": True,
}
class ScannerTestCase(unittest.TestCase):
def test_simple_parser(self) -> None:
parser = argparse.ArgumentParser(description="Process some integers.")
parser.add_argument(
"integers",
metavar="N",
type=int,
nargs="*",
help="an integer for the accumulator",
)
parser.add_argument(
"-i",
"--identity",
type=int,
default=0,
help="the default result for no arguments " "(default: 0)",
)
parser.add_argument(
"--sum",
dest="accumulate",
action="store_const",
const=sum,
default=max,
help="sum the integers (default: find the max)",
)
parser.add_argument("--key-value", metavar=("KEY", "VALUE"), nargs=2)
parser.add_argument("--max", help=argparse.SUPPRESS) # must be opt-out
programs = scan_programs(parser)
programs = list(programs)
self.assertEqual(1, len(programs))
(parser_info,) = programs
program, options, cmd_parser = parser_info
self.assertEqual([], program)
self.assertEqual("Process some integers.", cmd_parser.description)
self.assertEqual(5, len(options))
self.assertEqual((["n"], "an integer for the accumulator"), options[0])
self.assertEqual(
(["-h", "--help"], "show this help message and exit"), options[1]
)
self.assertEqual(
(
["-i ", "--identity "],
"the default result for no arguments (default: 0)",
),
options[2],
)
self.assertEqual(
(["--sum"], "sum the integers (default: find the max)"), options[3]
)
self.assertEqual(
(
[
"--key-value ",
],
"",
),
options[4],
)
def test_subcommands(self) -> None:
parser = argparse.ArgumentParser(description="Process some integers.")
subparsers = parser.add_subparsers()
max_parser = subparsers.add_parser("max", description="Find the max.")
max_parser.set_defaults(accumulate=max)
max_parser.add_argument(
"integers",
metavar="N",
type=int,
nargs="+",
help="An integer for the accumulator.",
)
sum_parser = subparsers.add_parser("sum", description="Sum the integers.")
sum_parser.set_defaults(accumulate=sum)
sum_parser.add_argument(
"integers",
metavar="N",
type=int,
nargs="+",
help="An integer for the accumulator.",
)
programs = scan_programs(parser)
programs = list(programs)
self.assertEqual(3, len(programs))
# main
program, options, cmd_parser = programs[0]
self.assertEqual([], program)
self.assertEqual("Process some integers.", cmd_parser.description)
self.assertEqual(1, len(options))
self.assertEqual(
(["-h", "--help"], "show this help message and exit"), options[0]
)
# max
program, options, cmd_parser = programs[1]
self.assertEqual(["max"], program)
self.assertEqual("Find the max.", cmd_parser.description)
self.assertEqual(2, len(options))
self.assertEqual((["n"], "An integer for the accumulator."), options[0])
self.assertEqual(
(["-h", "--help"], "show this help message and exit"), options[1]
)
# sum
program, options, cmd_parser = programs[2]
self.assertEqual(["sum"], program)
self.assertEqual("Sum the integers.", cmd_parser.description)
self.assertEqual(2, len(options))
self.assertEqual((["n"], "An integer for the accumulator."), options[0])
def test_argument_groups(self) -> None:
parser = argparse.ArgumentParser(description="This is a program.")
parser.add_argument("-v", action="store_true", help="A global argument")
plain_group = parser.add_argument_group(
"Plain Options", description="This is a group."
)
plain_group.add_argument(
"--plain", action="store_true", help="A plain argument."
)
fancy_group = parser.add_argument_group(
"Fancy Options", description="Another group."
)
fancy_group.add_argument("fancy", type=int, help="Set the fancyness")
sections = list(scan_programs(parser, groups=True))
self.assertEqual(4, len(sections))
# section: unnamed
program, options, cmd_parser = sections[0]
self.assertEqual([], program)
self.assertEqual("This is a program.", cmd_parser.description)
self.assertEqual(0, len(options))
# section: default optionals
program, options, group = sections[1]
self.assertEqual([], program)
# See https://github.com/sphinx-contrib/autoprogram/issues/24
if sys.version_info >= (3, 10):
self.assertEqual('options', group.title)
else:
self.assertEqual('optional arguments', group.title)
self.assertEqual(None, group.description)
self.assertEqual(2, len(options))
self.assertEqual(
(["-h", "--help"], "show this help message and exit"), options[0]
)
self.assertEqual((["-v"], "A global argument"), options[1])
# section: Plain Options
program, options, group = sections[2]
self.assertEqual([], program)
self.assertEqual("Plain Options", group.title)
self.assertEqual("This is a group.", group.description)
self.assertEqual(1, len(options))
self.assertEqual((["--plain"], "A plain argument."), options[0])
# section: Fancy Options
program, options, group = sections[3]
self.assertEqual([], program)
self.assertEqual("Fancy Options", group.title)
self.assertEqual("Another group.", group.description)
self.assertEqual(1, len(options))
self.assertEqual((["fancy"], "Set the fancyness"), options[0])
def test_choices(self) -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--awesomeness", choices=["meh", "awesome"])
_program, options, _cmd_parser = list(scan_programs(parser))[0]
log_option = options[1]
self.assertEqual((["--awesomeness {meh,awesome}"], ""), log_option)
def test_parse_epilog(self) -> None:
parser = argparse.ArgumentParser(
description="Process some integers.",
epilog="The integers will be processed.",
)
programs = scan_programs(parser)
programs = list(programs)
self.assertEqual(1, len(programs))
(parser_data,) = programs
_program, _options, cmd_parser = parser_data
self.assertEqual("The integers will be processed.", cmd_parser.epilog)
class AutoprogramDirectiveTestCase(unittest.TestCase):
def setUp(self) -> None:
self.untouched_sys_path = sys.path[:]
sample_prog_path = os.path.join(os.path.dirname(__file__), "..", "doc")
sys.path.insert(0, sample_prog_path)
self.directive = AutoprogramDirective(
"autoprogram",
["cli:parser"],
{"prog": "cli.py"},
StringList([], items=[]),
1,
0,
".. autoprogram:: cli:parser\n :prog: cli.py\n",
None,
mock.Mock(),
)
def tearDown(self) -> None:
sys.path[:] = self.untouched_sys_path
def test_make_rst(self) -> None:
self.assertEqual(
"\n".join(self.directive.make_rst()).strip(),
inspect.cleandoc(
"""
.. program:: cli.py
cli.py
??????
Process some integers.
.. code-block:: console
usage: cli.py [-h] [-i IDENTITY] [--sum] N [N ...]
.. option:: n
An integer for the accumulator.
.. option:: -h, --help
show this help message and exit
.. option:: -i , --identity
the default result for no arguments (default: 0)
.. option:: --sum
Sum the integers (default: find the max).
""").strip()
)
class UtilTestCase(unittest.TestCase):
def test_import_object(self) -> None:
cls = import_object("sphinxcontrib.autoprogram:UtilTestCase")
self.assertTrue(cls is UtilTestCase)
instance = import_object(
'sphinxcontrib.autoprogram:UtilTestCase("test_import_object")'
)
self.assertIsInstance(instance, UtilTestCase)
def test_import_object_filename(self) -> None:
with tempfile.TemporaryDirectory() as tmpdirname:
filename = os.path.join(tmpdirname, 'somefile')
with open(filename, 'w') as fp:
fp.write("bar = 42\n")
value = import_object("{}:bar".format(filename))
self.assertTrue(value == 42)
if not hasattr(unittest.TestCase, "assertIsInstance"):
def assertIsInstance(self, instance, cls) -> None: # type: ignore[override]
self.assertTrue(
isinstance(instance, cls),
"{0!r} is not an instance of {1.__module__}."
"{1.__name__}".format(instance, cls),
)
suite = unittest.TestSuite()
for test_case in ScannerTestCase, AutoprogramDirectiveTestCase, UtilTestCase:
suite.addTests(unittest.defaultTestLoader.loadTestsFromTestCase(test_case))
autoprogram-0.1.9/tox.ini 0000664 0000000 0000000 00000002463 14574374461 0015420 0 ustar 00root root 0000000 0000000 # Policy:
#
# Always support at least two major versions of Python and Sphinx: The latest,
# and the one just before that. For the latest major version of Sphinx, test
# against the latest three minor versions. For older major versions, test
# against the latest minor version until maintenance becomes a burden, then drop
# them.
[tox]
envlist = {py38,py39,py310,py311,py312}-{sphinx34,sphinx33,sphinx32,sphinx24,sphinx18}
minversion = 2.7.0
[testenv]
deps =
sphinx34: Sphinx >= 3.4.0, < 3.5.0
sphinx33: Sphinx >= 3.3.0, < 3.4.0
sphinx32: Sphinx >= 3.2.0, < 3.3.0
sphinx24: Sphinx >= 2.4.0, < 3.0.0
sphinx18: Sphinx >= 1.8.0, < 1.9.0
commands =
python setup.py test
[testenv:flake8]
deps =
flake8 >= 3.5.0, < 4.0.0
flake8-import-order-spoqa >= 1.3.0, < 2.0.0
commands =
flake8 sphinxcontrib/
[flake8]
exclude = build, dist, doc, .tox
import-order-style = spoqa
application-import-names = sphinxcontrib.autoprogram
max-line-length = 88
[testenv:doc]
basepython = python3
deps = -rdoc/rtd-requires.txt
commands =
python3 setup.py build_sphinx --build-dir=doc/_build
[testenv:black]
deps =
black
commands =
black --check --diff sphinxcontrib
[testenv:mypy]
deps =
mypy
commands =
mypy sphinxcontrib
[testenv:pylint]
deps =
pylint
commands =
pylint sphinxcontrib