pax_global_header 0000666 0000000 0000000 00000000064 14467763176 0014537 g ustar 00root root 0000000 0000000 52 comment=9c0f7d8d141abff4fcae4b9273ac385c6bbe9cf3
python-readme-renderer-41.0/ 0000775 0000000 0000000 00000000000 14467763176 0016043 5 ustar 00root root 0000000 0000000 python-readme-renderer-41.0/.github/ 0000775 0000000 0000000 00000000000 14467763176 0017403 5 ustar 00root root 0000000 0000000 python-readme-renderer-41.0/.github/workflows/ 0000775 0000000 0000000 00000000000 14467763176 0021440 5 ustar 00root root 0000000 0000000 python-readme-renderer-41.0/.github/workflows/ci.yml 0000664 0000000 0000000 00000002771 14467763176 0022565 0 ustar 00root root 0000000 0000000 name: CI
on: [push, pull_request]
jobs:
test:
name: Test - ${{ matrix.python-version }}
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["pypy-3.8", "3.8", "3.9", "3.10", "3.11"]
steps:
- name: Check out repository
uses: actions/checkout@v3
- name: Install Python
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}
check-latest: true
- name: Install dependencies
run: python -m pip install tox
- name: Run tests
run: |
python -m tox -e py
python -m tox -e noextra
lint:
name: Lint
runs-on: ubuntu-latest
steps:
- name: Check out repository
uses: actions/checkout@v3
- name: Install Python
uses: actions/setup-python@v4
with:
python-version: "3.x"
check-latest: true
- name: Install dependencies
run: python -m pip install tox
- name: Run linting
run: python -m tox -e pep8
- name: Run mypy
run: python -m tox -e mypy
packaging:
name: Packaging
runs-on: ubuntu-latest
steps:
- name: Check out repository
uses: actions/checkout@v3
- name: Install Python
uses: actions/setup-python@v4
with:
python-version: "3.x"
check-latest: true
- name: Install dependencies
run: python -m pip install tox
- name: Test packaging
run: python -m tox -e packaging
python-readme-renderer-41.0/.github/workflows/release.yml 0000664 0000000 0000000 00000001247 14467763176 0023607 0 ustar 00root root 0000000 0000000 name: Release
on:
release:
types: [published]
jobs:
build-and-publish:
runs-on: ubuntu-latest
permissions:
# IMPORTANT: this permission is mandatory for trusted publishing
id-token: write
steps:
- name: Checkout
uses: actions/checkout@v3
with:
ref: ${{ github.event.release.tag_name }}
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: "3.x"
check-latest: true
- name: Install build dependencies
run: pip install -U setuptools wheel build
- name: Build
run: python -m build .
- name: Publish
uses: pypa/gh-action-pypi-publish@release/v1
python-readme-renderer-41.0/.gitignore 0000664 0000000 0000000 00000000226 14467763176 0020033 0 ustar 00root root 0000000 0000000 __pycache__/
_build/
build/
dist/
htmlcov/
.tox/
.cache/
.coverage
*.egg-info/
*.egg
*.eggs
*.py[co]
.pytest_cache/
.python-version
.idea/
.vscode/
python-readme-renderer-41.0/.gitpod.yml 0000664 0000000 0000000 00000001260 14467763176 0020131 0 ustar 00root root 0000000 0000000 # See https://www.gitpod.io/docs/references/gitpod-yml for full reference
tasks:
- name: Setup Development and run Tests
init: |
# Upgrade pyenv itself
pyenv update
export PY_VERSIONS="3.8 3.9 3.10 3.11"
# Install all supported Python versions
for py in $PY_VERSIONS;
do pyenv install "$py":latest --skip-existing ;
done
# Make versions available via $PATH, exclude GitPod default
pyenv global $(pyenv versions --bare | grep -v 3.8.13)
# Install `tox` test orchestrator
pip install tox
command: tox
vscode:
extensions:
- ms-python.python
- EditorConfig.EditorConfig
- bungcip.better-toml
python-readme-renderer-41.0/CHANGES.rst 0000664 0000000 0000000 00000012617 14467763176 0017654 0 ustar 00root root 0000000 0000000 Changes
=======
41.0 (2023-08-18)
-----------------
* Allow HTML5 `figcaption` tag through cleaner (#291)
* Test `README.rst` from this project (#288)
40.0 (2023-06-16)
-----------------
* Add CLI option to render package README. (#271)
* Adapt tests to pygments 2.14.0 (#272)
* Update release process to use Trusted Publishing (#276)
* Replace usage of deprecated `pkg_resources` with `importlib.metadata` (#281)
* Drop support for Python 3.7 (#282), Test against Python 3.11 (#280)
37.3 (2022-10-31)
-----------------
* Allow HTML5 `figure` tag through cleaner (#265)
37.2 (2022-09-24)
-----------------
* Allow HTML5 `s` tag through cleaner (#261)
37.1 (2022-09-03)
-----------------
* Allow HTML5 `nav` tag through cleaner (#259)
37.0 (2022-08-21)
-----------------
* Remove command line example from docs (#197)
* Multiple pyproject.toml fixes (#251)
* Confirm handling multiple inline strong (#252)
* Convert RST output to HTML5 (#253)
* Add Typing to classifiers (#254)
* Development tweaks - coverage reporting, actions updates (#255)
* Add test confirming behavior with unknown lexers (#256)
36.0 (2022-08-06)
-----------------
* Enable gitpod development (#238)
* Allow rst admonitions to render (#242)
* Add badges to README (#243)
* Update codebase for modern Python (#244)
* Fix table cell spans (#245)
* Allow ``math`` directive in rst (#246)
* Preserve ``lang`` attribute in ``pre`` (#247)
35.0 (2022-04-19)
-----------------
* Add py.typed to the built wheel (#228)
* Use isolated build for tox (#229)
* Fix renderer ignore (#230)
* Remove legacy check command and distutils (#233)
* Emit a warning when no content is rendered (#231)
* Drop support for Python 3.6 (#236)
* Update html attribute order in tests (#235)
34.0 (2022-03-11)
-----------------
* Add static types (#225)
33.0 (2022-03-05)
-----------------
* Support cmarkgfm>=0.8.0 (#224)
33.0 (2022-02-05)
-----------------
* Support cmarkgfm>=0.8.0 (#224)
* Support Python 3.10
32.0 (2021-12-13)
-----------------
* Allow start attribute in ordered lists (#216)
* No limit rendering RST one column field names (#219)
31.0 (2021-12-09)
-----------------
* Render disabled checkboxes from Markdown (#217)
30.0 (2021-09-30)
-----------------
* support cmarkgfm>=0.6.0 (#209)
29.0 (2021-02-22)
-----------------
* Support cmarkgfm>=0.5.0 (#180)
* Drop support for Python 2 and 3.5 (#188)
28.0 (2020-10-20)
-----------------
* Support Python 3.9
27.0 (2020-10-09)
-----------------
* Add support for align attribute rendering Markdown headers (#173)
26.0 (2020-04-22)
-----------------
* Fix regression with image width/height attributes (#164)
25.0 (2020-03-14)
-----------------
* Support Python 3.7 and 3.8
* Drop support for Python 3.4
* Require Pygments>=2.5.1
24.0 (2018-10-27)
-----------------
* Remove dependency on ``future``. (#134)
23.0 (2018-10-22)
-----------------
* Breaking change: Move the cmarkgfm dependency into an extra (#130). Users
that want to render Markdown will need to install readme_render[md] instead.
22.0 (2018-09-17)
-----------------
* Unify handling of SVG and other images in RST. (#113)
* Support width and alignment of images in RST (#114)
21.0 (2018-05-28)
-----------------
* Allow
. (#105)
* Add specific tests for the raw directive. (#103)
* Include docinfo when rendering rst. (#99)
* Make Python 3 the default lexer for highlighting Python code in Markdown (#97)
* Allow align attribute on tags (#98)
20.0 (2018-04-13)
-----------------
* Reformat docutils messages into more human-friendly output. (#92)
* Fix incorrect escaping of html entities in pre tags when using markdown. (#89)
* Allow width, height, alt, and align attributes on img tags. (#91)
* Fix check to not report success when there is invalid RST. (#90)
19.0 (2018-04-10)
-----------------
* Allow details and summary tags. (#77)
* Add .pytest_cache to .gitignore. (#85)
* Warn about Markdown content type when checking RST. (#83)
* Update pep8 tox env to use py3.6. (#84)
* Add Pygments-based syntax highlighting for Markdown. (#82)
* Update docs about check to talk about Markdown. (#80)
18.1 (2018-04-01)
-----------------
* Change Github-flavored Markdown identifier from ``gfm`` to ``GFM``.
18.0 (2018-03-30)
-----------------
* Add support for GitHub-flavored Markdown. (#67)
* Switch to cmarkgfm completely for rendering Markdown. (#68)
* Warn about missing long description. (#69)
* Make Github-Flavored Markdown the default variant (#73)
17.4 (2018-03-16)
-----------------
* All renderers now accept arbitrary ``kwargs`` for future-proofing.
17.3 (2018-03-08)
-----------------
* Gracefully handle new exceptions from bleach.
17.2 (2017-03-11)
-----------------
* Fix an issue cleaning plaintext values.
17.1 (2017-03-09)
-----------------
* Fix an issue attempting to clean data that had ```` tags without a href.
17.0 (2017-03-08)
-----------------
* Fix issue with bleach >= 2.0.
16.0 (2016-12-09)
-----------------
* Fix issue with docutils >= 0.13.1.
0.7.0 (2016-01-04)
------------------
* Renamed to ``readme_renderer``: https://github.com/pypa/readme_renderer
to work around an name overlap with ``README`` files shipped in Python's
default site-packages directory on certain case-insensitive file systems.
* Added `PyPA Code of Conduct`_.
* Allow and tags when cleaning rST HTML output.
* Dropped support for Python 2.6.
.. _PyPA Code of Conduct: https://www.pypa.io/en/latest/code-of-conduct/
python-readme-renderer-41.0/LICENSE 0000664 0000000 0000000 00000022736 14467763176 0017062 0 ustar 00root root 0000000 0000000 Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
python-readme-renderer-41.0/MANIFEST.in 0000664 0000000 0000000 00000000356 14467763176 0017605 0 ustar 00root root 0000000 0000000 include LICENSE README.rst CHANGES.rst
include tox.ini
include readme_renderer/py.typed
recursive-include tests *.html
recursive-include tests *.py
recursive-include tests *.rst
recursive-include tests *.txt
recursive-include tests *.md
python-readme-renderer-41.0/README.rst 0000664 0000000 0000000 00000002342 14467763176 0017533 0 ustar 00root root 0000000 0000000 Readme Renderer
===============
.. image:: https://badge.fury.io/py/readme-renderer.svg
:target: https://badge.fury.io/py/readme-renderer
.. image:: https://github.com/pypa/readme_renderer/actions/workflows/ci.yml/badge.svg
:target: https://github.com/pypa/readme_renderer/actions/workflows/ci.yml
Readme Renderer is a library that will safely render arbitrary
``README`` files into HTML. It is designed to be used in Warehouse_ to
render the ``long_description`` for packages. It can handle Markdown,
reStructuredText (``.rst``), and plain text.
.. _Warehouse: https://github.com/pypa/warehouse
Check Description Locally
-------------------------
To locally check whether your long descriptions will render on PyPI, first
build your distributions, and then use the |twine check|_ command.
Code of Conduct
---------------
Everyone interacting in the readme_renderer project's codebases, issue trackers,
chat rooms, and mailing lists is expected to follow the `PSF Code of Conduct`_.
.. |twine check| replace:: ``twine check``
.. _twine check: https://packaging.python.org/guides/making-a-pypi-friendly-readme#validating-restructuredtext-markup
.. _PSF Code of Conduct: https://github.com/pypa/.github/blob/main/CODE_OF_CONDUCT.md
python-readme-renderer-41.0/pyproject.toml 0000664 0000000 0000000 00000001002 14467763176 0020750 0 ustar 00root root 0000000 0000000 [build-system]
requires = ["setuptools>=40.8.0"]
build-backend = "setuptools.build_meta"
# TODO: Remove when https://github.com/mgedmin/check-manifest/pull/155 released
[tool.check-manifest]
ignore = [".gitpod.yml"]
[tool.coverage.run]
branch = true
[tool.mypy]
strict = true
warn_unused_configs = true
show_error_codes = true
enable_error_code = [
"ignore-without-code"
]
[[tool.mypy.overrides]]
# These modules do not yet have types available.
module = [
"cmarkgfm.*"
]
ignore_missing_imports = true
python-readme-renderer-41.0/readme_renderer/ 0000775 0000000 0000000 00000000000 14467763176 0021166 5 ustar 00root root 0000000 0000000 python-readme-renderer-41.0/readme_renderer/__about__.py 0000664 0000000 0000000 00000002137 14467763176 0023451 0 ustar 00root root 0000000 0000000 # Copyright 2014 Donald Stufft
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
__all__ = [
"__title__",
"__summary__",
"__uri__",
"__version__",
"__author__",
"__email__",
"__license__",
"__copyright__",
]
__title__ = "readme_renderer"
__summary__ = (
'readme_renderer is a library for rendering "readme" ' "descriptions for Warehouse"
)
__uri__ = "https://github.com/pypa/readme_renderer"
__version__ = "41.0"
__author__ = "The Python Packaging Authority"
__email__ = "admin@mail.pypi.org"
__license__ = "Apache License, Version 2.0"
__copyright__ = "Copyright 2014 %s" % __author__
python-readme-renderer-41.0/readme_renderer/__init__.py 0000664 0000000 0000000 00000001075 14467763176 0023302 0 ustar 00root root 0000000 0000000 # Copyright 2014 Donald Stufft
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
python-readme-renderer-41.0/readme_renderer/__main__.py 0000664 0000000 0000000 00000005076 14467763176 0023270 0 ustar 00root root 0000000 0000000 import argparse
from readme_renderer.markdown import render as render_md
from readme_renderer.rst import render as render_rst
from readme_renderer.txt import render as render_txt
import pathlib
from importlib.metadata import metadata
import sys
from typing import Optional, List
def main(cli_args: Optional[List[str]] = None) -> None:
parser = argparse.ArgumentParser(
description="Renders a .md, .rst, or .txt README to HTML",
)
parser.add_argument("-p", "--package", help="Get README from package metadata",
action="store_true")
parser.add_argument("-f", "--format", choices=["md", "rst", "txt"],
help="README format (inferred from input file name or package)")
parser.add_argument('input', help="Input README file or package name")
parser.add_argument('-o', '--output', help="Output file (default: stdout)",
type=argparse.FileType('w'), default='-')
args = parser.parse_args(cli_args)
content_format = args.format
if args.package:
message = metadata(args.input)
source = message.get_payload() # type: ignore[attr-defined] # noqa: E501 https://peps.python.org/pep-0566/
# Infer the format of the description from package metadata.
if not content_format:
content_type = message.get("Description-Content-Type", "text/x-rst") # type: ignore[attr-defined] # noqa: E501 https://github.com/python/typeshed/issues/10021
if content_type == "text/x-rst":
content_format = "rst"
elif content_type == "text/markdown":
content_format = "md"
elif content_type == "text/plain":
content_format = "txt"
else:
raise ValueError(f"invalid content type {content_type} for package "
"`long_description`")
else:
filename = pathlib.Path(args.input)
content_format = content_format or filename.suffix.lstrip(".")
with filename.open() as fp:
source = fp.read()
if content_format == "md":
rendered = render_md(source, stream=sys.stderr)
elif content_format == "rst":
rendered = render_rst(source, stream=sys.stderr)
elif content_format == "txt":
rendered = render_txt(source, stream=sys.stderr)
else:
raise ValueError(f"invalid README format: {content_format} (expected `md`, "
"`rst`, or `txt`)")
if rendered is None:
sys.exit(1)
print(rendered, file=args.output)
if __name__ == '__main__':
main()
python-readme-renderer-41.0/readme_renderer/clean.py 0000664 0000000 0000000 00000010324 14467763176 0022622 0 ustar 00root root 0000000 0000000 # Copyright 2014 Donald Stufft
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import functools
from typing import Any, Dict, Iterator, List, Optional
import bleach
import bleach.callbacks
import bleach.linkifier
import bleach.sanitizer
ALLOWED_TAGS = [
# Bleach Defaults
"a", "abbr", "acronym", "b", "blockquote", "code", "em", "i", "li", "ol",
"strong", "ul",
# Custom Additions
"br", "caption", "cite", "col", "colgroup", "dd", "del", "details", "div",
"dl", "dt", "h1", "h2", "h3", "h4", "h5", "h6", "hr", "img", "p", "pre",
"span", "sub", "summary", "sup", "table", "tbody", "td", "th", "thead",
"tr", "tt", "kbd", "var", "input", "section", "aside", "nav", "s", "figure",
"figcaption",
]
ALLOWED_ATTRIBUTES = {
# Bleach Defaults
"a": ["href", "title"],
"abbr": ["title"],
"acronym": ["title"],
# Custom Additions
"*": ["id"],
"hr": ["class"],
"img": ["src", "width", "height", "alt", "align", "class"],
"span": ["class"],
"th": ["align", "class"],
"td": ["align", "colspan", "rowspan"],
"div": ["align", "class"],
"h1": ["align"],
"h2": ["align"],
"h3": ["align"],
"h4": ["align"],
"h5": ["align"],
"h6": ["align"],
"code": ["class"],
"p": ["align", "class"],
"pre": ["lang"],
"ol": ["start"],
"input": ["type", "checked", "disabled"],
"aside": ["class"],
"dd": ["class"],
"dl": ["class"],
"dt": ["class"],
"ul": ["class"],
"nav": ["class"],
"figure": ["class"],
}
class DisabledCheckboxInputsFilter:
# The typeshed for bleach (html5lib) filters is incomplete, use `typing.Any`
# See https://github.com/python/typeshed/blob/505ea726415016e53638c8b584b8fdc9c722cac1/stubs/bleach/bleach/html5lib_shim.pyi#L7-L8 # noqa E501
def __init__(self, source: Any) -> None:
self.source = source
def __iter__(self) -> Iterator[Dict[str, Optional[str]]]:
for token in self.source:
if token.get("name") == "input":
# only allow disabled checkbox inputs
is_checkbox, is_disabled, unsafe_attrs = False, False, False
for (_, attrname), value in token.get("data", {}).items():
if attrname == "type" and value == "checkbox":
is_checkbox = True
elif attrname == "disabled":
is_disabled = True
elif attrname != "checked":
unsafe_attrs = True
break
if is_checkbox and is_disabled and not unsafe_attrs:
yield token
else:
yield token
def __getattr__(self, name: str) -> Any:
return getattr(self.source, name)
def clean(
html: str,
tags: Optional[List[str]] = None,
attributes: Optional[Dict[str, List[str]]] = None
) -> Optional[str]:
if tags is None:
tags = ALLOWED_TAGS
if attributes is None:
attributes = ALLOWED_ATTRIBUTES
# Clean the output using Bleach
cleaner = bleach.sanitizer.Cleaner(
tags=tags,
attributes=attributes,
filters=[
# Bleach Linkify makes it easy to modify links, however, we will
# not be using it to create additional links.
functools.partial(
bleach.linkifier.LinkifyFilter,
callbacks=[
lambda attrs, new: attrs if not new else None,
bleach.callbacks.nofollow,
],
skip_tags=["pre"],
parse_email=False,
),
DisabledCheckboxInputsFilter,
],
)
try:
cleaned = cleaner.clean(html)
return cleaned
except ValueError:
return None
python-readme-renderer-41.0/readme_renderer/markdown.py 0000664 0000000 0000000 00000007013 14467763176 0023363 0 ustar 00root root 0000000 0000000 # Copyright 2014 Donald Stufft
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import re
import warnings
from typing import cast, Any, Dict, Callable, Match, Optional
from html import unescape
import pygments
import pygments.lexers
import pygments.formatters
from .clean import clean
_EXTRA_WARNING = (
"Markdown renderers are not available. "
"Install 'readme_renderer[md]' to enable Markdown rendering."
)
try:
import cmarkgfm
from cmarkgfm.cmark import Options as cmarkgfmOptions
variants: Dict[str, Callable[[str], str]] = {
"GFM": lambda raw: cast(str, cmarkgfm.github_flavored_markdown_to_html(
raw, options=cmarkgfmOptions.CMARK_OPT_UNSAFE
)),
"CommonMark": lambda raw: cast(str, cmarkgfm.markdown_to_html(
raw, options=cmarkgfmOptions.CMARK_OPT_UNSAFE
)),
}
except ImportError:
warnings.warn(_EXTRA_WARNING)
variants = {}
# Make code fences with `python` as the language default to highlighting as
# Python 3.
_LANG_ALIASES = {
'python': 'python3',
}
def render(
raw: str,
variant: str = "GFM",
**kwargs: Any
) -> Optional[str]:
if not variants:
warnings.warn(_EXTRA_WARNING)
return None
renderer = variants.get(variant)
if not renderer:
return None
rendered = renderer(raw)
if not rendered:
return None
highlighted = _highlight(rendered)
cleaned = clean(highlighted)
return cleaned
def _highlight(html: str) -> str:
"""Syntax-highlights HTML-rendered Markdown.
Plucks sections to highlight that conform the the GitHub fenced code info
string as defined at https://github.github.com/gfm/#info-string.
Args:
html (str): The rendered HTML.
Returns:
str: The HTML with Pygments syntax highlighting applied to all code
blocks.
"""
formatter = pygments.formatters.HtmlFormatter(nowrap=True)
code_expr = re.compile(
# cmarkgfm<0.6.0: print('hello')
# cmarkgfm>=0.6.0: print('hello')
r'((?P[^"]+?)">'
'(?(in_code)|)(?P.+?)'
r'
', re.DOTALL)
def replacer(match: Match[Any]) -> str:
try:
lang = match.group('lang')
lang = _LANG_ALIASES.get(lang, lang)
lexer = pygments.lexers.get_lexer_by_name(lang)
except ValueError:
lexer = pygments.lexers.TextLexer()
code = match.group('code')
# Decode html entities in the code. cmark tries to be helpful and
# translate '"' to '"', but it confuses pygments. Pygments will
# escape any html entities when re-writing the code, and we run
# everything through bleach after.
code = unescape(code)
highlighted = pygments.highlight(code, lexer, formatter)
return f'{highlighted} '
result = code_expr.sub(replacer, html)
return result
python-readme-renderer-41.0/readme_renderer/py.typed 0000664 0000000 0000000 00000000000 14467763176 0022653 0 ustar 00root root 0000000 0000000 python-readme-renderer-41.0/readme_renderer/rst.py 0000664 0000000 0000000 00000010554 14467763176 0022355 0 ustar 00root root 0000000 0000000 # Copyright 2014 Donald Stufft
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import io
from typing import Any, Dict, IO, Optional, Union
from docutils.core import publish_parts
from docutils.nodes import colspec, image
from docutils.writers.html5_polyglot import HTMLTranslator, Writer
from docutils.utils import SystemMessage
from .clean import clean
class ReadMeHTMLTranslator(HTMLTranslator): # type: ignore[misc] # docutils is incomplete, returns `Any` python/typeshed#7256 # noqa E501
# Overrides base class not to output `` tag for SVG images.
object_image_types: Dict[str, str] = {}
def emptytag(
self,
node: Union[colspec, image],
tagname: str,
suffix: str = "\n",
**attributes: Any
) -> Any:
"""Override this to add back the width/height attributes."""
if tagname == "img":
if "width" in node:
attributes["width"] = node["width"]
if "height" in node:
attributes["height"] = node["height"]
return super().emptytag(
node, tagname, suffix, **attributes
)
SETTINGS = {
# Cloaking email addresses provides a small amount of additional
# privacy protection for email addresses inside of a chunk of ReST.
"cloak_email_addresses": True,
# Prevent a lone top level heading from being promoted to document
# title, and thus second level headings from being promoted to top
# level.
"doctitle_xform": True,
# Prevent a lone subsection heading from being promoted to section
# title, and thus second level headings from being promoted to top
# level.
"sectsubtitle_xform": True,
# Set our initial header level
"initial_header_level": 2,
# Prevent local files from being included into the rendered output.
# This is a security concern because people can insert files
# that are part of the system, such as /etc/passwd.
"file_insertion_enabled": False,
# Halt rendering and throw an exception if there was any errors or
# warnings from docutils.
"halt_level": 2,
# Output math blocks as LaTeX that can be interpreted by MathJax for
# a prettier display of Math formulas.
# Pass a dummy path to supress docutils warning and emit HTML.
"math_output": "MathJax /dummy.js",
# Disable raw html as enabling it is a security risk, we do not want
# people to be able to include any old HTML in the final output.
"raw_enabled": False,
# Disable all system messages from being reported.
"report_level": 5,
# Use typographic quotes, and transform --, ---, and ... into their
# typographic counterparts.
"smart_quotes": True,
# Strip all comments from the rendered output.
"strip_comments": True,
# Use the short form of syntax highlighting so that the generated
# Pygments CSS can be used to style the output.
"syntax_highlight": "short",
# Maximum width (in characters) for one-column field names.
# 0 means "no limit"
"field_name_limit": 0,
}
def render(
raw: str,
stream: Optional[IO[str]] = None,
**kwargs: Any
) -> Optional[str]:
if stream is None:
# Use a io.StringIO as the warning stream to prevent warnings from
# being printed to sys.stderr.
stream = io.StringIO()
settings = SETTINGS.copy()
settings["warning_stream"] = stream
writer = Writer()
writer.translator_class = ReadMeHTMLTranslator
try:
parts = publish_parts(raw, writer=writer, settings_overrides=settings)
except SystemMessage:
rendered = None
else:
rendered = parts.get("docinfo", "") + parts.get("fragment", "")
if rendered:
return clean(rendered)
else:
# If the warnings stream is empty, docutils had none, so add ours.
if not stream.tell():
stream.write("No content rendered from RST source.")
return None
python-readme-renderer-41.0/readme_renderer/txt.py 0000664 0000000 0000000 00000001467 14467763176 0022367 0 ustar 00root root 0000000 0000000 # Copyright 2015 Donald Stufft
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import Any, Optional
from .clean import clean
from html import escape as html_escape
def render(raw: str, **kwargs: Any) -> Optional[str]:
rendered = html_escape(raw).replace("\n", " ")
return clean(rendered, tags=["br"])
python-readme-renderer-41.0/setup.cfg 0000664 0000000 0000000 00000000043 14467763176 0017661 0 ustar 00root root 0000000 0000000 [metadata]
license_files = LICENSE
python-readme-renderer-41.0/setup.py 0000664 0000000 0000000 00000004365 14467763176 0017565 0 ustar 00root root 0000000 0000000 # Copyright 2014 Donald Stufft
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pathlib
import setuptools
base_dir = pathlib.Path(__file__).parent
with open(base_dir.joinpath("readme_renderer", "__about__.py")) as f:
about = {}
exec(f.read(), about)
with open(base_dir.joinpath("README.rst")) as f:
long_description = f.read()
setuptools.setup(
name=about["__title__"],
version=about["__version__"],
description=about["__summary__"],
long_description=long_description,
license=about["__license__"],
url=about["__uri__"],
author=about["__author__"],
author_email=about["__email__"],
classifiers=[
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Natural Language :: English",
"Operating System :: MacOS :: MacOS X",
"Operating System :: POSIX",
"Operating System :: POSIX :: BSD",
"Operating System :: POSIX :: Linux",
"Operating System :: Microsoft :: Windows",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
"Typing :: Typed",
],
install_requires=["bleach>=2.1.0", "docutils>=0.13.1", "Pygments>=2.5.1"],
include_package_data=True,
extras_require={"md": "cmarkgfm>=0.8.0"},
packages=setuptools.find_packages(exclude=["tests", "tests.*"]),
python_requires=">=3.8",
)
python-readme-renderer-41.0/tests/ 0000775 0000000 0000000 00000000000 14467763176 0017205 5 ustar 00root root 0000000 0000000 python-readme-renderer-41.0/tests/__init__.py 0000664 0000000 0000000 00000000000 14467763176 0021304 0 ustar 00root root 0000000 0000000 python-readme-renderer-41.0/tests/fixtures/ 0000775 0000000 0000000 00000000000 14467763176 0021056 5 ustar 00root root 0000000 0000000 python-readme-renderer-41.0/tests/fixtures/test_CommonMark_001.html 0000664 0000000 0000000 00000000015 14467763176 0025422 0 ustar 00root root 0000000 0000000 Hello
python-readme-renderer-41.0/tests/fixtures/test_CommonMark_001.md 0000664 0000000 0000000 00000000006 14467763176 0025056 0 ustar 00root root 0000000 0000000 Hello
python-readme-renderer-41.0/tests/fixtures/test_CommonMark_002.html 0000664 0000000 0000000 00000000043 14467763176 0025424 0 ustar 00root root 0000000 0000000 http://mymalicioussite.com/
python-readme-renderer-41.0/tests/fixtures/test_CommonMark_002.md 0000664 0000000 0000000 00000000034 14467763176 0025060 0 ustar 00root root 0000000 0000000 http://mymalicioussite.com/
python-readme-renderer-41.0/tests/fixtures/test_CommonMark_003.html 0000664 0000000 0000000 00000000242 14467763176 0025426 0 ustar 00root root 0000000 0000000 Required packages
To run the PyPI software, you need Python 2.5+ and PostgreSQL
Quick development setup
Make sure you are sitting
python-readme-renderer-41.0/tests/fixtures/test_CommonMark_003.md 0000664 0000000 0000000 00000000212 14467763176 0025057 0 ustar 00root root 0000000 0000000 ## Required packages
To run the PyPI software, you need Python 2.5+ and PostgreSQL
## Quick development setup
Make sure you are sitting
python-readme-renderer-41.0/tests/fixtures/test_CommonMark_004.html 0000664 0000000 0000000 00000000242 14467763176 0025427 0 ustar 00root root 0000000 0000000 Required packages
To run the PyPI software, you need Python 2.5+ and PostgreSQL
Quick development setup
Make sure you are sitting
python-readme-renderer-41.0/tests/fixtures/test_CommonMark_004.md 0000664 0000000 0000000 00000000241 14467763176 0025062 0 ustar 00root root 0000000 0000000 Required packages
To run the PyPI software, you need Python 2.5+ and PostgreSQL
Quick development setup
Make sure you are sitting