|
From: <mi...@us...> - 2024-07-28 10:50:25
|
Revision: 9781
http://sourceforge.net/p/docutils/code/9781
Author: milde
Date: 2024-07-28 10:50:23 +0000 (Sun, 28 Jul 2024)
Log Message:
-----------
rST parser warns about empty footnotes and citations.
The reStructuredText parser now adds a "warning"-level system
message for footnotes and citations without content block
instead of generating invalid elements.
(Block-level content is mandatory for `<footnote>` and `<citation>`
elements according to the Docutils DTD.)
Modified Paths:
--------------
trunk/docutils/HISTORY.txt
trunk/docutils/docutils/parsers/rst/states.py
trunk/docutils/test/test_parsers/test_rst/test_citations.py
trunk/docutils/test/test_parsers/test_rst/test_footnotes.py
trunk/docutils/test/test_writers/test_latex2e.py
trunk/docutils/test/test_writers/test_manpage.py
Modified: trunk/docutils/HISTORY.txt
===================================================================
--- trunk/docutils/HISTORY.txt 2024-07-28 10:50:12 UTC (rev 9780)
+++ trunk/docutils/HISTORY.txt 2024-07-28 10:50:23 UTC (rev 9781)
@@ -84,6 +84,10 @@
- Renamed `normalized_role_options()` to `normalized_role_options()`
(it is now also used for directive options).
+* docutils/parsers/rst/states.py
+
+ - Raise warning for empty footnotes and citations.
+
* docutils/readers/__init__.py:
- Deprecate "parser_name" argument of `Reader.__init__()`.
Modified: trunk/docutils/docutils/parsers/rst/states.py
===================================================================
--- trunk/docutils/docutils/parsers/rst/states.py 2024-07-28 10:50:12 UTC (rev 9780)
+++ trunk/docutils/docutils/parsers/rst/states.py 2024-07-28 10:50:23 UTC (rev 9781)
@@ -1913,6 +1913,8 @@
self.document.set_id(footnote, footnote)
if indented:
self.nested_parse(indented, input_offset=offset, node=footnote)
+ else:
+ footnote += self.reporter.warning('Footnote content expected.')
return [footnote], blank_finish
def citation(self, match):
@@ -1930,6 +1932,8 @@
self.document.note_explicit_target(citation, citation)
if indented:
self.nested_parse(indented, input_offset=offset, node=citation)
+ else:
+ citation += self.reporter.warning('Citation content expected.')
return [citation], blank_finish
def hyperlink_target(self, match):
Modified: trunk/docutils/test/test_parsers/test_rst/test_citations.py
===================================================================
--- trunk/docutils/test/test_parsers/test_rst/test_citations.py 2024-07-28 10:50:12 UTC (rev 9780)
+++ trunk/docutils/test/test_parsers/test_rst/test_citations.py 2024-07-28 10:50:23 UTC (rev 9781)
@@ -120,11 +120,14 @@
<citation ids="citation" names="citation">
<label>
citation
+ <system_message level="2" line="2" source="test data" type="WARNING">
+ <paragraph>
+ Citation content expected.
<paragraph>
That was an empty citation.
"""],
["""\
-.. [citation]
+.. [citation] The Source
No blank line.
""",
"""\
@@ -132,6 +135,8 @@
<citation ids="citation" names="citation">
<label>
citation
+ <paragraph>
+ The Source
<system_message level="2" line="2" source="test data" type="WARNING">
<paragraph>
Explicit markup ends without a blank line; unexpected unindent.
Modified: trunk/docutils/test/test_parsers/test_rst/test_footnotes.py
===================================================================
--- trunk/docutils/test/test_parsers/test_rst/test_footnotes.py 2024-07-28 10:50:12 UTC (rev 9780)
+++ trunk/docutils/test/test_parsers/test_rst/test_footnotes.py 2024-07-28 10:50:23 UTC (rev 9781)
@@ -100,20 +100,24 @@
whose block starts on line 2.
"""],
["""\
+An empty footnote raises a warning:
+
.. [1]
-That was an empty footnote.
""",
"""\
<document source="test data">
+ <paragraph>
+ An empty footnote raises a warning:
<footnote ids="footnote-1" names="1">
<label>
1
- <paragraph>
- That was an empty footnote.
+ <system_message level="2" line="4" source="test data" type="WARNING">
+ <paragraph>
+ Footnote content expected.
"""],
["""\
-.. [1]
+.. [1] spamalot
No blank line.
""",
"""\
@@ -121,6 +125,8 @@
<footnote ids="footnote-1" names="1">
<label>
1
+ <paragraph>
+ spamalot
<system_message level="2" line="2" source="test data" type="WARNING">
<paragraph>
Explicit markup ends without a blank line; unexpected unindent.
Modified: trunk/docutils/test/test_writers/test_latex2e.py
===================================================================
--- trunk/docutils/test/test_writers/test_latex2e.py 2024-07-28 10:50:12 UTC (rev 9780)
+++ trunk/docutils/test/test_writers/test_latex2e.py 2024-07-28 10:50:23 UTC (rev 9781)
@@ -56,7 +56,6 @@
def test_defaults(self):
settings = self.settings.copy()
- settings['validate'] = False # we test an invalid footnote
self.run_samples(samples_default, settings)
def test_docutils_toc(self):
@@ -328,9 +327,7 @@
["""\
.. [1] paragraph
-.. [2]
-
-.. [3] 1. enumeration
+.. [2] 1. enumeration
""",
# expected output
head_template.substitute(dict(parts,
@@ -353,9 +350,7 @@
paragraph
}
%
-\DUfootnotetext{footnote-2}{footnote-2}{2}{}
-%
-\DUfootnotetext{footnote-3}{footnote-3}{3}{
+\DUfootnotetext{footnote-2}{footnote-2}{2}{
\begin{enumerate}
\item enumeration
\end{enumerate}
Modified: trunk/docutils/test/test_writers/test_manpage.py
===================================================================
--- trunk/docutils/test/test_writers/test_manpage.py 2024-07-28 10:50:12 UTC (rev 9780)
+++ trunk/docutils/test/test_writers/test_manpage.py 2024-07-28 10:50:23 UTC (rev 9781)
@@ -30,6 +30,7 @@
("me...@ho...", r"me@\:home.here"),
)
+
class URIBreakpointsTestCase(unittest.TestCase):
def test_insert(self):
@@ -53,7 +54,6 @@
settings_overrides={
'_disable_config': True,
'strict_visitor': True,
- 'validate': False, # allow testing invalid doctree
}).decode()
self.assertEqual(case_expected, output)
@@ -417,7 +417,7 @@
totest['citation'] = [
[""".. [docutils] blah blah blah
-.. [empty_citation]
+.. [citation2] Another Source
""",
document_start + indend_macros + """.TH "" "" "" ""
.SH Name
@@ -424,7 +424,8 @@
\\- \n\
.IP [docutils] 5
blah blah blah
-.IP [empty_citation] 5
+.IP [citation2] 5
+Another Source
.\\" End of generated man page.
"""],
]
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mi...@us...> - 2024-07-29 12:37:05
|
Revision: 9782
http://sourceforge.net/p/docutils/code/9782
Author: milde
Date: 2024-07-29 12:37:02 +0000 (Mon, 29 Jul 2024)
Log Message:
-----------
Remove mistranslations of the "admonition" directive name.
Some localizations used the translation of "admonition (reprimand)"
(not applicable for the rST directive)
instead of "admonition (advice/advisory/remark)".
Modified Paths:
--------------
trunk/docutils/HISTORY.txt
trunk/docutils/RELEASE-NOTES.txt
trunk/docutils/docutils/parsers/rst/languages/af.py
trunk/docutils/docutils/parsers/rst/languages/da.py
trunk/docutils/docutils/parsers/rst/languages/de.py
trunk/docutils/docutils/parsers/rst/languages/eo.py
trunk/docutils/docutils/parsers/rst/languages/es.py
trunk/docutils/docutils/parsers/rst/languages/fi.py
trunk/docutils/docutils/parsers/rst/languages/fr.py
trunk/docutils/docutils/parsers/rst/languages/gl.py
trunk/docutils/docutils/parsers/rst/languages/it.py
trunk/docutils/docutils/parsers/rst/languages/nl.py
trunk/docutils/docutils/parsers/rst/languages/pl.py
trunk/docutils/docutils/parsers/rst/languages/pt_br.py
trunk/docutils/docutils/parsers/rst/languages/sv.py
Modified: trunk/docutils/HISTORY.txt
===================================================================
--- trunk/docutils/HISTORY.txt 2024-07-28 10:50:23 UTC (rev 9781)
+++ trunk/docutils/HISTORY.txt 2024-07-29 12:37:02 UTC (rev 9782)
@@ -64,6 +64,10 @@
- New parser for Docutils XML sources. Provisional.
+* docutils/parsers/rst/languages/*.py
+
+ - Removed mistranslations of the "admonition" directive name.
+
* docutils/parsers/recommonmark_wrapper.py
- New method `Parser.finish_parse()` to clean up (before validating).
Modified: trunk/docutils/RELEASE-NOTES.txt
===================================================================
--- trunk/docutils/RELEASE-NOTES.txt 2024-07-28 10:50:23 UTC (rev 9781)
+++ trunk/docutils/RELEASE-NOTES.txt 2024-07-29 12:37:02 UTC (rev 9782)
@@ -90,7 +90,7 @@
specification of the aspect ratio to `prevent jank when loading
images`__ without overwriting an image size set in a CSS stylesheet
in Docutils 0.22 (cf. `feature-requests:102`__).
- The current behaviour is kept for dimensions with value, so
+ The current behaviour is kept for dimensions with units, so
users may specify, e.g. ``:width: 50px`` instead of ``:width: 50``
to override CSS stylesheet rules.
@@ -171,16 +171,6 @@
__ docs/ref/transforms.html
-* Remove mistranslated localizations of the "admonition" directive name in
- Docutils 0.22.
-
- Use the English term, matching translations introduced in Docutils 0.21,
- or specific admonitions instead of "aanmaning" (nl),
- "admonition" (fr), "ammonizione" (it), "ermahnung" (de),
- "exhortación" (es), "formaning" (da), "sciigo" (eo),
- "upomnienie" (pl), "vermaning" (af),
- to avoid errors in future conversions.
-
.. _front end tools: docs/user/tools.html
.. _input_encoding: docs/user/config.html#input-encoding
.. _math_output: docs/user/config.html#math-output
@@ -242,20 +232,27 @@
Removed objects
`docutils.core.Publisher.setup_option_parser()`
- internal, obsolete
+ internal, obsolete,
`docutils.nodes.Element.set_class()`
- Obsolete. Append to Element['classes'] directly.
+ obsolete, append to Element['classes'] directly,
`docutils.parsers.rst.directives.tables.CSVTable.decode_from_csv()`
- not required with Python 3
+ not required with Python 3,
`docutils.parsers.rst.directives.tables.CSVTable.encode_from_csv()`
- not required with Python 3
+ not required with Python 3,
`docutils.transforms.writer_aux.Compound`
- not used since Dec 2010
+ not used since Dec 2010,
`docutils.utils.error_reporting`
- obsolete in Python 3
+ obsolete in Python 3,
`docutils.utils.Reporter.set_conditions()`
- Obsolete. Set attributes via configuration settings or directly.
+ obsolete, set attributes via configuration settings or directly.
+Removed localisations:
+ Mistranslations of the "admonition" directive name:
+ Use "advies" (af), "varsel" (da), "warnhinweis" (de), "aviso" (es),
+ "sciigo" (eo), "annonce" (fr), "avviso" (it), "advies" (nl),
+ "zauważenie" (pl) (introduced in Docutils 0.21)
+ or the English name "admonition".
+
Removed files
``tools/rst2odt_prepstyles.py``
Obsoleted by `docutils.writers.odf_odt.prepstyles`.
Modified: trunk/docutils/docutils/parsers/rst/languages/af.py
===================================================================
--- trunk/docutils/docutils/parsers/rst/languages/af.py 2024-07-28 10:50:23 UTC (rev 9781)
+++ trunk/docutils/docutils/parsers/rst/languages/af.py 2024-07-29 12:37:02 UTC (rev 9782)
@@ -27,7 +27,6 @@
'tip': 'tip', # hint and tip both have the same translation: wenk
'waarskuwing': 'warning',
'advies': 'admonition',
- 'vermaning': 'admonition', # sic! kept for backwards compatibiltity
'kantstreep': 'sidebar',
'onderwerp': 'topic',
'lynblok': 'line-block',
Modified: trunk/docutils/docutils/parsers/rst/languages/da.py
===================================================================
--- trunk/docutils/docutils/parsers/rst/languages/da.py 2024-07-28 10:50:23 UTC (rev 9781)
+++ trunk/docutils/docutils/parsers/rst/languages/da.py 2024-07-29 12:37:02 UTC (rev 9782)
@@ -30,7 +30,6 @@
'tips': 'tip',
'advarsel': 'warning',
'varsel': 'admonition',
- 'formaning': 'admonition', # sic! kept for backwards compatibiltity
'sidebjælke': 'sidebar',
'emne': 'topic',
'linje-blok': 'line-block',
Modified: trunk/docutils/docutils/parsers/rst/languages/de.py
===================================================================
--- trunk/docutils/docutils/parsers/rst/languages/de.py 2024-07-28 10:50:23 UTC (rev 9781)
+++ trunk/docutils/docutils/parsers/rst/languages/de.py 2024-07-29 12:37:02 UTC (rev 9782)
@@ -18,7 +18,6 @@
directives = {
'warnhinweis': 'admonition', # or, more generally, 'anmerkung'?
- 'ermahnung': 'admonition', # sic! kept for backwards compatibiltity
'achtung': 'attention',
'vorsicht': 'caution',
'code': 'code',
Modified: trunk/docutils/docutils/parsers/rst/languages/eo.py
===================================================================
--- trunk/docutils/docutils/parsers/rst/languages/eo.py 2024-07-28 10:50:23 UTC (rev 9781)
+++ trunk/docutils/docutils/parsers/rst/languages/eo.py 2024-07-29 12:37:02 UTC (rev 9782)
@@ -29,7 +29,6 @@
'helpeto': 'tip',
'averto': 'warning',
'sciigo': 'admonition',
- 'admono': 'admonition', # sic! kept for backwards compatibiltity
'flankteksto': 'sidebar',
'temo': 'topic',
'linea-bloko': 'line-block',
Modified: trunk/docutils/docutils/parsers/rst/languages/es.py
===================================================================
--- trunk/docutils/docutils/parsers/rst/languages/es.py 2024-07-28 10:50:23 UTC (rev 9781)
+++ trunk/docutils/docutils/parsers/rst/languages/es.py 2024-07-29 12:37:02 UTC (rev 9782)
@@ -28,8 +28,6 @@
'consejo': 'tip',
'advertencia': 'warning',
'aviso': 'admonition',
- 'exhortacion': 'admonition', # sic! kept for backwards compatibiltity
- 'exhortación': 'admonition', # sic! kept for backwards compatibiltity
'nota-al-margen': 'sidebar',
'tema': 'topic',
'bloque-de-lineas': 'line-block',
Modified: trunk/docutils/docutils/parsers/rst/languages/fi.py
===================================================================
--- trunk/docutils/docutils/parsers/rst/languages/fi.py 2024-07-28 10:50:23 UTC (rev 9781)
+++ trunk/docutils/docutils/parsers/rst/languages/fi.py 2024-07-29 12:37:02 UTC (rev 9782)
@@ -17,6 +17,7 @@
directives = {
# language-dependent: fixed
+ 'admonition (translation required)': 'admonition',
'huomio': 'attention',
'varo': 'caution',
'code (translation required)': 'code',
@@ -27,7 +28,6 @@
'huomautus': 'note',
'neuvo': 'tip',
'varoitus': 'warning',
- 'kehotus': 'admonition', # sic! advice/advisory/remark, not reprimand
'sivupalkki': 'sidebar',
'aihe': 'topic',
'rivi': 'line-block',
Modified: trunk/docutils/docutils/parsers/rst/languages/fr.py
===================================================================
--- trunk/docutils/docutils/parsers/rst/languages/fr.py 2024-07-28 10:50:23 UTC (rev 9781)
+++ trunk/docutils/docutils/parsers/rst/languages/fr.py 2024-07-29 12:37:02 UTC (rev 9782)
@@ -26,7 +26,6 @@
'astuce': 'tip',
'avertissement': 'warning',
'annonce': 'admonition',
- 'admonition': 'admonition', # sic! kept for backwards compatibiltity
# suggestions: annonce, avis, indication, remarque, renseignement
# see also https://sourceforge.net/p/docutils/bugs/453/
'encadré': 'sidebar',
Modified: trunk/docutils/docutils/parsers/rst/languages/gl.py
===================================================================
--- trunk/docutils/docutils/parsers/rst/languages/gl.py 2024-07-28 10:50:23 UTC (rev 9781)
+++ trunk/docutils/docutils/parsers/rst/languages/gl.py 2024-07-29 12:37:02 UTC (rev 9782)
@@ -19,6 +19,7 @@
directives = {
# language-dependent: fixed
+ 'admonition (translation required)': 'admonition',
'atención': 'attention',
'advertencia': 'caution',
'code (translation required)': 'code',
@@ -29,7 +30,6 @@
'nota': 'note',
'consello': 'tip',
'aviso': 'warning',
- 'admonición': 'admonition', # sic! advice/advisory/remark, not reprimand
'barra lateral': 'sidebar',
'tópico': 'topic',
'bloque-liña': 'line-block',
Modified: trunk/docutils/docutils/parsers/rst/languages/it.py
===================================================================
--- trunk/docutils/docutils/parsers/rst/languages/it.py 2024-07-28 10:50:23 UTC (rev 9781)
+++ trunk/docutils/docutils/parsers/rst/languages/it.py 2024-07-29 12:37:02 UTC (rev 9782)
@@ -28,7 +28,6 @@
'consiglio': 'tip',
'avvertenza': 'warning',
'avviso': 'admonition',
- 'ammonizione': 'admonition', # sic! kept for backards compatibility
'riquadro': 'sidebar',
'argomento': 'topic',
'blocco-di-righe': 'line-block',
Modified: trunk/docutils/docutils/parsers/rst/languages/nl.py
===================================================================
--- trunk/docutils/docutils/parsers/rst/languages/nl.py 2024-07-28 10:50:23 UTC (rev 9781)
+++ trunk/docutils/docutils/parsers/rst/languages/nl.py 2024-07-29 12:37:02 UTC (rev 9782)
@@ -28,7 +28,6 @@
'tip': 'tip',
'waarschuwing': 'warning',
'advies': 'admonition',
- 'aanmaning': 'admonition', # sic! kept for backwards compatibiltity
'katern': 'sidebar',
'onderwerp': 'topic',
'lijn-blok': 'line-block',
Modified: trunk/docutils/docutils/parsers/rst/languages/pl.py
===================================================================
--- trunk/docutils/docutils/parsers/rst/languages/pl.py 2024-07-28 10:50:23 UTC (rev 9781)
+++ trunk/docutils/docutils/parsers/rst/languages/pl.py 2024-07-29 12:37:02 UTC (rev 9782)
@@ -28,7 +28,6 @@
'rada': 'tip',
'ostrzeżenie': 'warning',
'zauważenie': 'admonition', # remark
- 'upomnienie': 'admonition', # sic! kept for backwards compatibiltity
'ramka': 'sidebar',
'temat': 'topic',
'blok-linii': 'line-block',
Modified: trunk/docutils/docutils/parsers/rst/languages/pt_br.py
===================================================================
--- trunk/docutils/docutils/parsers/rst/languages/pt_br.py 2024-07-28 10:50:23 UTC (rev 9781)
+++ trunk/docutils/docutils/parsers/rst/languages/pt_br.py 2024-07-29 12:37:02 UTC (rev 9782)
@@ -28,7 +28,6 @@
'dica': 'tip',
'aviso': 'warning',
'advertência': 'admonition',
- 'exortação': 'admonition', # sic! advice/advisory/remark, not reprimand
'barra-lateral': 'sidebar',
'tópico': 'topic',
'bloco-de-linhas': 'line-block',
Modified: trunk/docutils/docutils/parsers/rst/languages/sv.py
===================================================================
--- trunk/docutils/docutils/parsers/rst/languages/sv.py 2024-07-28 10:50:23 UTC (rev 9781)
+++ trunk/docutils/docutils/parsers/rst/languages/sv.py 2024-07-29 12:37:02 UTC (rev 9782)
@@ -24,7 +24,7 @@
'notera': 'note',
'tips': 'tip',
'varning': 'warning',
- 'anmärkning': 'admonition', # literal 'tillrättavisning', 'förmaning'
+ 'anmärkning': 'admonition',
'sidorad': 'sidebar',
'ämne': 'topic',
'tema': 'topic',
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mi...@us...> - 2024-07-29 12:37:29
|
Revision: 9783
http://sourceforge.net/p/docutils/code/9783
Author: milde
Date: 2024-07-29 12:37:21 +0000 (Mon, 29 Jul 2024)
Log Message:
-----------
LaTeX writer: simplify handling of the "reference_label" customization setting.
Don't wrap references with custom reference-label_ in a `\hyperref` command.
because the "hyperref" LaTeX package creates a hyperlink by default.
Modified Paths:
--------------
trunk/docutils/HISTORY.txt
trunk/docutils/RELEASE-NOTES.txt
trunk/docutils/docutils/writers/latex2e/__init__.py
Modified: trunk/docutils/HISTORY.txt
===================================================================
--- trunk/docutils/HISTORY.txt 2024-07-29 12:37:02 UTC (rev 9782)
+++ trunk/docutils/HISTORY.txt 2024-07-29 12:37:21 UTC (rev 9783)
@@ -64,7 +64,7 @@
- New parser for Docutils XML sources. Provisional.
-* docutils/parsers/rst/languages/*.py
+* docutils/parsers/rst/languages/
- Removed mistranslations of the "admonition" directive name.
@@ -144,7 +144,11 @@
- Remove optional argument `pxunit` of `LaTeXTranslator.to_latex_length()`
(ignored since at least 2012).
+ - Don't wrap references with custom reference-label_ in
+ a ``\hyperref`` command.
+ .. _reference-label: docs/user/config.html#reference-label
+
* docutils/writers/manpage.py
- Remove code for unused emdash bullets.
@@ -931,7 +935,7 @@
- Open ``docutils.sty`` with encoding set to "utf-8".
Fixes bug #414: error with Py3k when locale encoding is "ascii".
-* docutils/parsers/*.py, docutils/transforms/*.py
+* docutils/parsers/ docutils/transforms/
- Provide fallbacks for parser config settings
to facilitate programmatic use.
Modified: trunk/docutils/RELEASE-NOTES.txt
===================================================================
--- trunk/docutils/RELEASE-NOTES.txt 2024-07-29 12:37:02 UTC (rev 9782)
+++ trunk/docutils/RELEASE-NOTES.txt 2024-07-29 12:37:21 UTC (rev 9783)
@@ -77,8 +77,9 @@
* "html5" writer:
- - Move attribution behind the blockquote to comply with the `"living
- standard"`__. (HTML5__ allows <cite> elements inside a blockquote.)
+ - Move attribution behind the blockquote to comply with the
+ `"HTML living standard"`__. (The now retired HTML5__ W3C recommendation
+ allows <cite> elements inside a blockquote.)
__ https://html.spec.whatwg.org/#the-blockquote-element
__ https://www.w3.org/TR/2014/REC-html5-20141028/grouping-content.html
@@ -115,12 +116,6 @@
- Remove ``use_verbatim_when_possible`` setting
(use literal_block_env_: verbatim) in Docutils 2.0.
- - Don't wrap references with custom reference-label_ in
- a ``\hyperref`` command in Docutils 0.22.
- Specify, e.g., "ref" instead of "ref*" to keep generating hyperlinks.
-
- .. _reference-label: docs/user/config.html#reference-label
-
Misc
----
@@ -216,6 +211,13 @@
`publish_string()` now returns a `bytes` or `str` instance
for all writers (as documented).
+ "latex" writer:
+ Don't wrap references with custom reference-label_ in a ``\hyperref``
+ command. The "hyperref" package generates hyperlinks for labels by
+ default, so there is no change in the PDF (except for "ref*").
+
+ .. _reference-label: docs/user/config.html#reference-label
+
New objects
`parsers.docutils_xml`
parser for `Docutils XML`_ (e.g., the output of the "xml" writer).
Modified: trunk/docutils/docutils/writers/latex2e/__init__.py
===================================================================
--- trunk/docutils/docutils/writers/latex2e/__init__.py 2024-07-29 12:37:02 UTC (rev 9782)
+++ trunk/docutils/docutils/writers/latex2e/__init__.py 2024-07-29 12:37:21 UTC (rev 9783)
@@ -2838,12 +2838,11 @@
raise AssertionError('Unknown reference.')
if not self.is_inline(node):
self.out.append('\n')
- self.out.append('\\hyperref[%s]{' % href)
if self.reference_label:
- # TODO: don't use \hyperref if self.reference_label is True
- self.out.append('\\%s{%s}}' %
+ self.out.append('\\%s{%s}' %
(self.reference_label, href.replace('#', '')))
raise nodes.SkipNode
+ self.out.append('\\hyperref[%s]{' % href)
def depart_reference(self, node):
self.out.append('}')
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <aa-...@us...> - 2024-07-31 02:23:55
|
Revision: 9785
http://sourceforge.net/p/docutils/code/9785
Author: aa-turner
Date: 2024-07-31 02:23:32 +0000 (Wed, 31 Jul 2024)
Log Message:
-----------
Fix tests on Windows
Mostly path separator problems.
Modified Paths:
--------------
trunk/docutils/docutils/writers/_html_base.py
trunk/docutils/test/test_CLI.py
trunk/docutils/test/test_utils/test__init__.py
trunk/docutils/test/test_writers/test_html5_polyglot_parts.py
Modified: trunk/docutils/docutils/writers/_html_base.py
===================================================================
--- trunk/docutils/docutils/writers/_html_base.py 2024-07-30 23:52:51 UTC (rev 9784)
+++ trunk/docutils/docutils/writers/_html_base.py 2024-07-31 02:23:32 UTC (rev 9785)
@@ -22,7 +22,8 @@
import os.path
from pathlib import Path
import re
-import urllib
+import urllib.parse
+import urllib.request
import warnings
import xml.etree.ElementTree as ET # TODO: lazy import in prepare_svg()?
@@ -628,7 +629,7 @@
if uri_parts.scheme not in ('', 'file'):
raise ValueError('Can only read local images.')
imagepath = urllib.request.url2pathname(uri_parts.path)
- if imagepath.startswith('/'):
+ if imagepath.startswith(('/', '\\')): # UNIX- or Windows-style
root_prefix = Path(self.settings.root_prefix)
imagepath = (root_prefix/imagepath[1:]).as_posix()
elif not os.path.isabs(imagepath): # exclude absolute Windows paths
Modified: trunk/docutils/test/test_CLI.py
===================================================================
--- trunk/docutils/test/test_CLI.py 2024-07-30 23:52:51 UTC (rev 9784)
+++ trunk/docutils/test/test_CLI.py 2024-07-31 02:23:32 UTC (rev 9785)
@@ -58,7 +58,8 @@
sys.stdout = self.orig_stdout
sys.argv = self.orig_argv
# restore default locale settings:
- locale.setlocale(locale.LC_MESSAGES, 'C')
+ if sys.platform != "win32":
+ locale.setlocale(locale.LC_MESSAGES, 'C')
locale.setlocale(locale.LC_TIME, 'C')
def get_help_text(self, prog, entry_point):
Modified: trunk/docutils/test/test_utils/test__init__.py
===================================================================
--- trunk/docutils/test/test_utils/test__init__.py 2024-07-30 23:52:51 UTC (rev 9784)
+++ trunk/docutils/test/test_utils/test__init__.py 2024-07-31 02:23:32 UTC (rev 9785)
@@ -339,7 +339,7 @@
source = r'C:\foo\bar\fileA'
target = os.path.join('eggs', 'fileB')
self.assertEqual(utils.relative_path(source, target),
- os.path.abspath('eggs/fileB'))
+ os.path.abspath('eggs/fileB').replace('\\', '/'))
# Correctly process characters outside the ASCII range:
self.assertEqual(utils.relative_path('spam', 'spam'), '')
source = os.path.join('häm', 'spam', 'fileA')
Modified: trunk/docutils/test/test_writers/test_html5_polyglot_parts.py
===================================================================
--- trunk/docutils/test/test_writers/test_html5_polyglot_parts.py 2024-07-30 23:52:51 UTC (rev 9784)
+++ trunk/docutils/test/test_writers/test_html5_polyglot_parts.py 2024-07-31 02:23:32 UTC (rev 9785)
@@ -66,6 +66,10 @@
'</aside>\n')
+def relpath(path: Path) -> str:
+ return path.relative_to(Path.cwd()).as_posix()
+
+
class Html5WriterPublishPartsTestCase(unittest.TestCase):
"""Test case for HTML writer via the publish_parts interface."""
@@ -542,7 +546,7 @@
""",
}],
[f"""\
-.. include:: {DATA_ROOT}/multiple-term-definition.xml
+.. include:: {relpath(DATA_ROOT / 'multiple-term-definition.xml')}
:parser: xml
""",
{'fragment': """\
@@ -714,7 +718,7 @@
""",
}],
[f"""\
-.. image:: {DATA_ROOT}/circle-broken.svg
+.. image:: {relpath(DATA_ROOT / 'circle-broken.svg')}
:loading: embed
""",
{'fragment': f"""\
@@ -725,7 +729,7 @@
<aside class="system-message">
<p class="system-message-title">System Message: ERROR/3 (<span class="docutils literal"><string></span>, line 1)</p>
-<p>Cannot parse SVG image "{DATA_ROOT}/circle-broken.svg":
+<p>Cannot parse SVG image "{relpath(DATA_ROOT / 'circle-broken.svg')}":
not well-formed (invalid token): line 3, column 48</p>
</aside>
"""
@@ -831,7 +835,7 @@
""",
}],
[f"""\
-.. image:: {DATA_ROOT}/circle-broken.svg
+.. image:: {relpath(DATA_ROOT / 'circle-broken.svg')}
:loading: embed
""",
{'fragment': """\
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <aa-...@us...> - 2024-07-31 08:35:50
|
Revision: 9795
http://sourceforge.net/p/docutils/code/9795
Author: aa-turner
Date: 2024-07-31 08:35:47 +0000 (Wed, 31 Jul 2024)
Log Message:
-----------
Add an initial configuration file for Ruff
This reflects the current flake8 settings, save diagnostics
that Ruff does not implement. Ruff's detection of unused variables
seems to be greater than flake8's, so also fix several instances
and add some more files to the per-file ignore list.
Modified Paths:
--------------
trunk/docutils/docutils/core.py
trunk/docutils/docutils/parsers/rst/directives/tables.py
trunk/docutils/docutils/parsers/rst/languages/ka.py
trunk/docutils/docutils/writers/latex2e/__init__.py
trunk/docutils/docutils/writers/manpage.py
trunk/docutils/test/test_dependencies.py
trunk/docutils/test/test_parsers/test_rst/test_TableParser.py
trunk/docutils/test/test_statemachine.py
trunk/docutils/tools/test/test_buildhtml.py
Added Paths:
-----------
trunk/docutils/.ruff.toml
Added: trunk/docutils/.ruff.toml
===================================================================
--- trunk/docutils/.ruff.toml (rev 0)
+++ trunk/docutils/.ruff.toml 2024-07-31 08:35:47 UTC (rev 9795)
@@ -0,0 +1,143 @@
+target-version = "py39" # Pin Ruff to Python 3.9
+line-length = 88
+output-format = "full"
+
+[lint]
+preview = true
+select = [
+ "E", # pycodestyle
+ "F", # pyflakes
+ "W", # pycodestyle
+]
+ignore = [
+ "E226", # missing whitespace around arithmetic operator
+ "E228", # missing whitespace around modulo operator
+ # not generally frowned on by PEP 8:
+ # "If operators with different priorities are used, consider adding
+ # whitespace around the operators with the lowest priority(ies).
+ # Use your own judgment; …"
+]
+
+[lint.per-file-ignores]
+# class definitions with "…: pass" on one line
+"docutils/__init__.py" = [
+ "E302",
+ "E701",
+]
+"docutils/nodes.py" = [
+ "E302",
+ "E701",
+]
+"docutils/io.py" = [
+ "E302",
+ "E701",
+]
+"docutils/statemachine.py" = [
+ "E302",
+ "E701",
+ "F841",
+]
+"docutils/utils/__init__.py" = [
+ "E302",
+ "E701",
+]
+
+# complex regexp definitions
+"docutils/parsers/rst/states.py" = [
+ "E302",
+ "E701",
+ "F841",
+]
+# deprecated module, will be removed
+"docutils/utils/error_reporting.py" = [
+ "E261",
+]
+
+# module with 3rd-party origin
+"docutils/utils/math/math2html.py" = [
+ "E241",
+ "E501",
+ "E731",
+]
+
+# generated auxiliary files
+"docutils/utils/math/tex2unichar.py" = [
+ "E262",
+ "E501",
+]
+"docutils/utils/math/mathalphabet2unichar.py" = [
+ "E501",
+]
+
+# allow aligning values in data-collections
+"docutils/utils/smartquotes.py" = [
+ "E241",
+]
+"docutils/utils/roman.py" = [
+ "E241",
+ "E701",
+]
+"docutils/utils/math/latex2mathml.py" = [
+ "E221",
+ "E241",
+ "E272",
+ "E501",
+ "E701",
+]
+"docutils/writers/xetex/__init__.py" = [
+ "E241",
+]
+
+# also allow '##' to mark deactivated code:
+"docutils/writers/latex2e/__init__.py" = [
+ "E241",
+ "E266",
+]
+
+# ignore unused variables
+"docutils/parsers/rst/directives/misc.py" = [
+ "F841",
+]
+"docutils/writers/odf_odt/__init__.py" = [
+ "F841",
+]
+
+# included configuration files referencing externally defined variables
+"test/functional/tests/*" = [
+ "F821",
+]
+
+# deprecated module, will be removed
+"test/test_error_reporting.py" = [
+ "E261",
+]
+
+# Lists with multi-line test output samples
+# may contain long lines (E501)
+# and are not indented (E122, E124, E128)
+"test/test_parsers/*" = [
+ "E501",
+]
+"test/test_publisher.py" = [
+ "E501",
+]
+"test/test_readers/test_pep/*" = [
+ "E501",
+]
+"test/test_transforms/*" = [
+ "E501",
+]
+"test/test_writers/*" = [
+ "E501",
+]
+
+# test output contains trailing whitespace, long lines, operator at end
+"test/test_writers/test_manpage.py" = [
+ "W291",
+ "E501",
+]
+
+# ignore long line in string templates
+"tools/dev/generate_punctuation_chars.py" = [
+ "E501",
+]
Modified: trunk/docutils/docutils/core.py
===================================================================
--- trunk/docutils/docutils/core.py 2024-07-31 07:45:30 UTC (rev 9794)
+++ trunk/docutils/docutils/core.py 2024-07-31 08:35:47 UTC (rev 9795)
@@ -438,7 +438,7 @@
# The "*_name" arguments are deprecated.
_name_arg_warning(reader_name, parser_name, writer_name)
# The default is set in publish_programmatically().
- output, publisher = publish_programmatically(
+ output, _publisher = publish_programmatically(
source_class=io.FileInput, source=source, source_path=source_path,
destination_class=io.FileOutput,
destination=destination, destination_path=destination_path,
@@ -480,7 +480,7 @@
# The "*_name" arguments are deprecated.
_name_arg_warning(reader_name, parser_name, writer_name)
# The default is set in publish_programmatically().
- output, publisher = publish_programmatically(
+ output, _publisher = publish_programmatically(
source_class=io.StringInput, source=source, source_path=source_path,
destination_class=io.StringOutput,
destination=None, destination_path=destination_path,
@@ -521,7 +521,7 @@
# The "*_name" arguments are deprecated.
_name_arg_warning(reader_name, parser_name, writer_name)
# The default is set in publish_programmatically().
- output, publisher = publish_programmatically(
+ _output, publisher = publish_programmatically(
source=source, source_path=source_path, source_class=source_class,
destination_class=io.StringOutput,
destination=None, destination_path=destination_path,
Modified: trunk/docutils/docutils/parsers/rst/directives/tables.py
===================================================================
--- trunk/docutils/docutils/parsers/rst/directives/tables.py 2024-07-31 07:45:30 UTC (rev 9794)
+++ trunk/docutils/docutils/parsers/rst/directives/tables.py 2024-07-31 08:35:47 UTC (rev 9795)
@@ -430,7 +430,7 @@
node = nodes.Element() # anonymous container for parsing
self.state.nested_parse(self.content, self.content_offset, node)
try:
- num_cols, col_widths = self.check_list_content(node)
+ _num_cols, col_widths = self.check_list_content(node)
table_data = [[item.children for item in row_list[0]]
for row_list in node[0]]
header_rows = self.options.get('header-rows', 0)
Modified: trunk/docutils/docutils/parsers/rst/languages/ka.py
===================================================================
--- trunk/docutils/docutils/parsers/rst/languages/ka.py 2024-07-31 07:45:30 UTC (rev 9794)
+++ trunk/docutils/docutils/parsers/rst/languages/ka.py 2024-07-31 08:35:47 UTC (rev 9795)
@@ -44,7 +44,6 @@
'ნაგულისხმევი-როლი': 'default-role',
'სათაური': 'title',
'განყ-ნომერი': 'sectnum',
- 'განყ-ნომერი': 'sectnum',
'საფრთხე': 'danger',
'ფრთხილად': 'caution',
'შეცდომა': 'error',
Modified: trunk/docutils/docutils/writers/latex2e/__init__.py
===================================================================
--- trunk/docutils/docutils/writers/latex2e/__init__.py 2024-07-31 07:45:30 UTC (rev 9794)
+++ trunk/docutils/docutils/writers/latex2e/__init__.py 2024-07-31 08:35:47 UTC (rev 9795)
@@ -1202,10 +1202,10 @@
self.literal_block_env = ''
self.literal_block_options = ''
if settings.literal_block_env:
- (none,
+ (_none,
self.literal_block_env,
self.literal_block_options,
- none) = re.split(r'(\w+)(.*)', settings.literal_block_env)
+ _none) = re.split(r'(\w+)(.*)', settings.literal_block_env)
elif settings.use_verbatim_when_possible:
self.literal_block_env = 'verbatim'
Modified: trunk/docutils/docutils/writers/manpage.py
===================================================================
--- trunk/docutils/docutils/writers/manpage.py 2024-07-31 07:45:30 UTC (rev 9794)
+++ trunk/docutils/docutils/writers/manpage.py 2024-07-31 08:35:47 UTC (rev 9795)
@@ -747,7 +747,7 @@
pass
def visit_footnote(self, node):
- num, text = node.astext().split(None, 1)
+ num, _text = node.astext().split(maxsplit=1)
num = num.strip()
self.body.append('.IP [%s] 5\n' % self.deunicode(num))
Modified: trunk/docutils/test/test_dependencies.py
===================================================================
--- trunk/docutils/test/test_dependencies.py 2024-07-31 07:45:30 UTC (rev 9794)
+++ trunk/docutils/test/test_dependencies.py 2024-07-31 08:35:47 UTC (rev 9795)
@@ -76,7 +76,7 @@
if PIL and os.path.exists('../docs/user/rst/images/'):
keys += ['figure-image']
expected = [paths[key] for key in keys]
- record, output = self.get_record(writer='xml')
+ record, _output = self.get_record(writer='xml')
# the order of the files is arbitrary
self.assertEqual(sorted(expected), sorted(record))
@@ -123,23 +123,23 @@
'stylesheet': None}
settings.update(latex_settings_overwrites)
settings['embed_stylesheet'] = False
- record, output = self.get_record(writer='html',
- settings_overrides=settings)
+ record, _output = self.get_record(writer='html',
+ settings_overrides=settings)
self.assertTrue(stylesheet not in record,
f'{stylesheet!r} should not be in {record!r}')
- record, output = self.get_record(writer='latex',
- settings_overrides=settings)
+ record, _output = self.get_record(writer='latex',
+ settings_overrides=settings)
self.assertTrue(stylesheet not in record,
f'{stylesheet!r} should not be in {record!r}')
settings['embed_stylesheet'] = True
- record, output = self.get_record(writer='html',
- settings_overrides=settings)
+ record, _output = self.get_record(writer='html',
+ settings_overrides=settings)
self.assertTrue(stylesheet in record,
f'{stylesheet!r} should be in {record!r}')
settings['embed_stylesheet'] = True
- record, output = self.get_record(writer='latex',
- settings_overrides=settings)
+ record, _output = self.get_record(writer='latex',
+ settings_overrides=settings)
self.assertTrue(stylesheet in record,
f'{stylesheet!r} should be in {record!r}')
Modified: trunk/docutils/test/test_parsers/test_rst/test_TableParser.py
===================================================================
--- trunk/docutils/test/test_parsers/test_rst/test_TableParser.py 2024-07-31 07:45:30 UTC (rev 9794)
+++ trunk/docutils/test/test_parsers/test_rst/test_TableParser.py 2024-07-31 08:35:47 UTC (rev 9795)
@@ -25,7 +25,7 @@
parser = tableparser.GridTableParser()
for name, cases in totest.items():
for casenum, case in enumerate(cases):
- case_input, case_table, case_expected = case
+ case_input, case_table, _case_expected = case
lines_input = StringList(string2lines(case_input), 'test data')
parser.setup(lines_input)
try:
@@ -40,7 +40,7 @@
parser = tableparser.GridTableParser()
for name, cases in totest.items():
for casenum, case in enumerate(cases):
- case_input, case_table, case_expected = case
+ case_input, _case_table, case_expected = case
lines_input = StringList(string2lines(case_input), 'test data')
with self.subTest(id=f'totest[{name!r}][{casenum}]'):
try:
Modified: trunk/docutils/test/test_statemachine.py
===================================================================
--- trunk/docutils/test/test_statemachine.py 2024-07-31 07:45:30 UTC (rev 9794)
+++ trunk/docutils/test/test_statemachine.py 2024-07-31 08:35:47 UTC (rev 9795)
@@ -102,7 +102,7 @@
return [match.string], next_state, ['text%s' % self.level]
def literalblock(self):
- indented, indent, offset, good = self.state_machine.get_indented()
+ _indented, indent, _offset, _good = self.state_machine.get_indented()
if self.debug:
print('literalblock%s(%s)' % (self.level, indent), file=sys.stderr)
return ['literalblock%s(%s)' % (self.level, indent)]
Modified: trunk/docutils/tools/test/test_buildhtml.py
===================================================================
--- trunk/docutils/tools/test/test_buildhtml.py 2024-07-31 07:45:30 UTC (rev 9794)
+++ trunk/docutils/tools/test/test_buildhtml.py 2024-07-31 08:35:47 UTC (rev 9795)
@@ -34,7 +34,9 @@
BUILDHTML_PATH = TOOLS_ROOT / 'buildhtml.py'
-def process_and_return_filelist(options: list[str]) -> tuple[list[str], list[str]]:
+def process_and_return_filelist(
+ options: list[str],
+) -> tuple[list[str], list[str]]:
dirs = []
files = []
ret = subprocess.run(
@@ -80,7 +82,7 @@
def test_1(self):
opts = ["--dry-run", str(self.root)]
- dirs, files = process_and_return_filelist(opts)
+ _dirs, files = process_and_return_filelist(opts)
self.assertEqual(files.count("one.txt"), 4)
def test_local(self):
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <aa-...@us...> - 2024-07-31 09:17:29
|
Revision: 9796
http://sourceforge.net/p/docutils/code/9796
Author: aa-turner
Date: 2024-07-31 09:17:26 +0000 (Wed, 31 Jul 2024)
Log Message:
-----------
Do not recommend using flit as a build frontend
Instead, use the simpler ``build`` tool.
Also update pyproject.toml metadata.
Modified Paths:
--------------
trunk/docutils/docs/dev/release.txt
trunk/docutils/pyproject.toml
Modified: trunk/docutils/docs/dev/release.txt
===================================================================
--- trunk/docutils/docs/dev/release.txt 2024-07-31 08:35:47 UTC (rev 9795)
+++ trunk/docutils/docs/dev/release.txt 2024-07-31 09:17:26 UTC (rev 9796)
@@ -63,11 +63,6 @@
* Generate wheel and source-distribution::
- python3 -m pip install flit
- python3 -m flit build
-
- or ::
-
python3 -m pip install build
python3 -m build .
@@ -128,7 +123,7 @@
* Update your source directory.
* Rebuild wheel and source-distribution ::
- python3 -m flit build
+ python3 -m build
* Now upload to pypi::
Modified: trunk/docutils/pyproject.toml
===================================================================
--- trunk/docutils/pyproject.toml 2024-07-31 08:35:47 UTC (rev 9795)
+++ trunk/docutils/pyproject.toml 2024-07-31 09:17:26 UTC (rev 9796)
@@ -1,6 +1,7 @@
# Project configuration file for the "docutils" package (see PEP 518)
-# Build with flit (https://flit.pypa.io/)
+# Use flit as a build backend (https://flit.pypa.io/)
+# Build with (https://build.pypa.io/)
[build-system]
requires = ["flit_core>=3.4,<4"]
build-backend = "flit_core.buildapi"
@@ -8,9 +9,7 @@
# Project metadata
# cf. https://packaging.python.org/en/latest/specifications/declaring-project-metadata/
[project]
-
name = "docutils"
-dynamic = ["version"]
description = "Docutils -- Python Documentation Utilities"
readme.text = """
Docutils is a modular system for processing documentation
@@ -18,11 +17,8 @@
input Docutils supports reStructuredText, an easy-to-read,
what-you-see-is-what-you-get plaintext markup syntax.""" # wrap at col 60
readme.content-type = "text/plain"
-
urls.Homepage = "https://docutils.sourceforge.io"
-
license.file = "COPYING.txt"
-
requires-python = ">=3.9"
# cf. https://pypi.org/trove-classifiers/
@@ -77,6 +73,7 @@
'Natural Language :: Swedish',
'Natural Language :: Ukrainian',
]
+dynamic = ["version"]
[[project.authors]]
name = "David Goodger"
@@ -103,7 +100,6 @@
# Sdist (*.tar.gz) generation
[tool.flit.sdist]
-# required as ``flit --use-vcs`` only works for git and hg (current default)
# TODO: include generated HTML ?
include = [
"*.txt",
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <aa-...@us...> - 2024-07-31 12:59:35
|
Revision: 9805
http://sourceforge.net/p/docutils/code/9805
Author: aa-turner
Date: 2024-07-31 12:59:29 +0000 (Wed, 31 Jul 2024)
Log Message:
-----------
Add type hints to ``docutils.frontend``
Modified Paths:
--------------
trunk/docutils/docutils/frontend.py
trunk/docutils/test/test_settings.py
Modified: trunk/docutils/docutils/frontend.py
===================================================================
--- trunk/docutils/docutils/frontend.py 2024-07-31 10:44:49 UTC (rev 9804)
+++ trunk/docutils/docutils/frontend.py 2024-07-31 12:59:29 UTC (rev 9805)
@@ -50,6 +50,8 @@
`make_paths_absolute()`, `filter_settings_spec()`. Provisional.
"""
+from __future__ import annotations
+
__docformat__ = 'reStructuredText'
@@ -56,18 +58,39 @@
import codecs
import configparser
import optparse
-from optparse import SUPPRESS_HELP
import os
import os.path
-from pathlib import Path
import sys
import warnings
+from optparse import SUPPRESS_HELP
+from pathlib import Path
+from typing import TYPE_CHECKING
import docutils
from docutils import io, utils
+if TYPE_CHECKING:
+ from collections.abc import Iterable, Mapping, Sequence
+ from typing import Any, ClassVar, Literal, Protocol
-def store_multiple(option, opt, value, parser, *args, **kwargs):
+ from docutils import SettingsSpec, _OptionTuple, _SettingsSpecTuple
+
+ class _OptionValidator(Protocol):
+ def __call__( # NoQA: E704
+ self,
+ setting: str,
+ value: str | None,
+ option_parser: OptionParser,
+ /,
+ config_parser: ConfigParser | None = None,
+ config_section: str | None = None,
+ ) -> Any: ...
+
+
+def store_multiple(
+ option: optparse.Option, opt: str, value: Any, parser: OptionParser,
+ *args: str, **kwargs: Any,
+) -> None:
"""
Store multiple values in `parser.values`. (Option callback.)
@@ -80,7 +103,9 @@
setattr(parser.values, key, value)
-def read_config_file(option, opt, value, parser):
+def read_config_file(
+ option: optparse.Option, opt: str, value: Any, parser: OptionParser,
+) -> None:
"""
Read a configuration file during option processing. (Option callback.)
"""
@@ -91,8 +116,13 @@
parser.values.update(new_settings, parser)
-def validate_encoding(setting, value=None, option_parser=None,
- config_parser=None, config_section=None):
+def validate_encoding(
+ setting: str,
+ value: str | None = None,
+ option_parser: OptionParser | None = None,
+ config_parser: ConfigParser | None = None,
+ config_section: str | None = None,
+) -> str | None:
# All arguments except `value` are ignored
# (kept for compatibility with "optparse" module).
# If there is only one positional argument, it is interpreted as `value`.
@@ -110,8 +140,13 @@
return value
-def validate_encoding_error_handler(setting, value=None, option_parser=None,
- config_parser=None, config_section=None):
+def validate_encoding_error_handler(
+ setting: str,
+ value: str | None = None,
+ option_parser: OptionParser | None = None,
+ config_parser: ConfigParser | None = None,
+ config_section: str | None = None,
+) -> str:
# All arguments except `value` are ignored
# (kept for compatibility with "optparse" module).
# If there is only one positional argument, it is interpreted as `value`.
@@ -129,7 +164,12 @@
def validate_encoding_and_error_handler(
- setting, value, option_parser, config_parser=None, config_section=None):
+ setting: str,
+ value: str | None = None,
+ option_parser: OptionParser | None = None,
+ config_parser: ConfigParser | None = None,
+ config_section: str | None = None,
+) -> str:
"""
Side-effect: if an error handler is included in the value, it is inserted
into the appropriate place as if it were a separate setting/option.
@@ -147,8 +187,13 @@
return validate_encoding(encoding)
-def validate_boolean(setting, value=None, option_parser=None,
- config_parser=None, config_section=None):
+def validate_boolean(
+ setting: str | bool,
+ value: str | None = None,
+ option_parser: OptionParser | None = None,
+ config_parser: ConfigParser | None = None,
+ config_section: str | None = None,
+) -> bool:
"""Check/normalize boolean settings:
True: '1', 'on', 'yes', 'true'
False: '0', 'off', 'no','false', ''
@@ -167,8 +212,13 @@
raise LookupError('unknown boolean value: "%s"' % value)
-def validate_ternary(setting, value=None, option_parser=None,
- config_parser=None, config_section=None):
+def validate_ternary(
+ setting: str | bool,
+ value: str | None = None,
+ option_parser: OptionParser | None = None,
+ config_parser: ConfigParser | None = None,
+ config_section: str | None = None,
+) -> str | bool | None:
"""Check/normalize three-value settings:
True: '1', 'on', 'yes', 'true'
False: '0', 'off', 'no','false', ''
@@ -188,8 +238,13 @@
return value
-def validate_nonnegative_int(setting, value=None, option_parser=None,
- config_parser=None, config_section=None):
+def validate_nonnegative_int(
+ setting: str,
+ value: str | None = None,
+ option_parser: OptionParser | None = None,
+ config_parser: ConfigParser | None = None,
+ config_section: str | None = None,
+) -> int:
# All arguments except `value` are ignored
# (kept for compatibility with "optparse" module).
# If there is only one positional argument, it is interpreted as `value`.
@@ -201,8 +256,13 @@
return value
-def validate_threshold(setting, value=None, option_parser=None,
- config_parser=None, config_section=None):
+def validate_threshold(
+ setting: str,
+ value: str | None = None,
+ option_parser: OptionParser | None = None,
+ config_parser: ConfigParser | None = None,
+ config_section: str | None = None,
+) -> int:
# All arguments except `value` are ignored
# (kept for compatibility with "optparse" module).
# If there is only one positional argument, it is interpreted as `value`.
@@ -218,8 +278,12 @@
def validate_colon_separated_string_list(
- setting, value=None, option_parser=None,
- config_parser=None, config_section=None):
+ setting: str | list[str],
+ value: str | None = None,
+ option_parser: OptionParser | None = None,
+ config_parser: ConfigParser | None = None,
+ config_section: str | None = None,
+) -> list[str]:
# All arguments except `value` are ignored
# (kept for compatibility with "optparse" module).
# If there is only one positional argument, it is interpreted as `value`.
@@ -233,8 +297,13 @@
return value
-def validate_comma_separated_list(setting, value=None, option_parser=None,
- config_parser=None, config_section=None):
+def validate_comma_separated_list(
+ setting: str | list[str] | list[str | tuple[str, str]],
+ value: str | None = None,
+ option_parser: OptionParser | None = None,
+ config_parser: ConfigParser | None = None,
+ config_section: str | None = None,
+) -> list[str]:
"""Check/normalize list arguments (split at "," and strip whitespace).
All arguments except `value` are ignored
@@ -255,8 +324,13 @@
return value
-def validate_math_output(setting, value=None, option_parser=None,
- config_parser=None, config_section=None):
+def validate_math_output(
+ setting: str,
+ value: str | None = None,
+ option_parser: OptionParser | None = None,
+ config_parser: ConfigParser | None = None,
+ config_section: str | None = None,
+) -> tuple[()] | tuple[str, str]:
"""Check "math-output" setting, return list with "format" and "options".
See also https://docutils.sourceforge.io/docs/user/config.html#math-output
@@ -272,7 +346,7 @@
tex2mathml_converters = ('', 'latexml', 'ttm', 'blahtexml', 'pandoc')
if not value:
- return []
+ return ()
values = value.split(maxsplit=1)
format = values[0].lower()
try:
@@ -288,11 +362,16 @@
raise LookupError(f'MathML converter "{options}" not supported,\n'
f' choose from {tex2mathml_converters}.')
options = converter
- return [format, options]
+ return format, options
-def validate_url_trailing_slash(setting, value=None, option_parser=None,
- config_parser=None, config_section=None):
+def validate_url_trailing_slash(
+ setting: str | None,
+ value: str | None = None,
+ option_parser: OptionParser | None = None,
+ config_parser: ConfigParser | None = None,
+ config_section: str | None = None,
+) -> str:
# All arguments except `value` are ignored
# (kept for compatibility with "optparse" module).
# If there is only one positional argument, it is interpreted as `value`.
@@ -306,8 +385,13 @@
return value + '/'
-def validate_dependency_file(setting, value=None, option_parser=None,
- config_parser=None, config_section=None):
+def validate_dependency_file(
+ setting: str | None,
+ value: str | None = None,
+ option_parser: OptionParser | None = None,
+ config_parser: ConfigParser | None = None,
+ config_section: str | None = None,
+) -> utils.DependencyList:
# All arguments except `value` are ignored
# (kept for compatibility with "optparse" module).
# If there is only one positional argument, it is interpreted as `value`.
@@ -320,8 +404,13 @@
return utils.DependencyList(None)
-def validate_strip_class(setting, value=None, option_parser=None,
- config_parser=None, config_section=None):
+def validate_strip_class(
+ setting: str,
+ value: str | None = None,
+ option_parser: OptionParser | None = None,
+ config_parser: ConfigParser | None = None,
+ config_section: str | None = None,
+) -> list[str]:
# All arguments except `value` are ignored
# (kept for compatibility with "optparse" module).
# If there is only one positional argument, it is interpreted as `value`.
@@ -338,8 +427,13 @@
return value
-def validate_smartquotes_locales(setting, value=None, option_parser=None,
- config_parser=None, config_section=None):
+def validate_smartquotes_locales(
+ setting: str | list[str | tuple[str, str]],
+ value: str | None = None,
+ option_parser: OptionParser | None = None,
+ config_parser: ConfigParser | None = None,
+ config_section: str | None = None,
+) -> list[tuple[str, Sequence[str]]]:
"""Check/normalize a comma separated list of smart quote definitions.
Return a list of (language-tag, quotes) string tuples.
@@ -379,7 +473,11 @@
return lc_quotes
-def make_paths_absolute(pathdict, keys, base_path=None):
+def make_paths_absolute(
+ pathdict: dict[str, list[str | os.PathLike[str]] | str | os.PathLike[str]],
+ keys: list[str],
+ base_path: str | os.PathLike[str] | None = None,
+) -> None:
"""
Interpret filesystem path settings relative to the `base_path` given.
@@ -402,7 +500,9 @@
pathdict[key] = value
-def make_one_path_absolute(base_path, path):
+def make_one_path_absolute(
+ base_path: str | os.PathLike[str], path: str | os.PathLike[str],
+) -> str:
# deprecated, will be removed
warnings.warn('frontend.make_one_path_absolute() will be removed '
'in Docutils 0.23.', DeprecationWarning, stacklevel=2)
@@ -409,7 +509,11 @@
return os.path.abspath(os.path.join(base_path, path))
-def filter_settings_spec(settings_spec, *exclude, **replace):
+def filter_settings_spec(
+ settings_spec: _SettingsSpecTuple,
+ *exclude: str,
+ **replace: _OptionTuple,
+) -> _SettingsSpecTuple:
"""Return a copy of `settings_spec` excluding/replacing some settings.
`settings_spec` is a tuple of configuration settings
@@ -422,7 +526,7 @@
settings = list(settings_spec)
# every third item is a sequence of option tuples
for i in range(2, len(settings), 3):
- newopts = []
+ newopts: list[_OptionTuple] = []
for opt_spec in settings[i]:
# opt_spec is ("<help>", [<option strings>], {<keyword args>})
opt_name = [opt_string[2:].replace('-', '_')
@@ -447,16 +551,20 @@
Deprecated. Will be removed.
"""
- def __init__(self, *args, **kwargs):
+ def __init__(self, defaults: dict[str, Any] | None = None) -> None:
warnings.warn('frontend.Values class will be removed '
'in Docutils 0.21 or later.',
DeprecationWarning, stacklevel=2)
- super().__init__(*args, **kwargs)
+ super().__init__(defaults=defaults)
if getattr(self, 'record_dependencies', None) is None:
# Set up dummy dependency list.
self.record_dependencies = utils.DependencyList()
- def update(self, other_dict, option_parser):
+ def update(
+ self,
+ other_dict: Values | Mapping[str, Any],
+ option_parser: OptionParser,
+ ) -> None:
if isinstance(other_dict, Values):
other_dict = other_dict.__dict__
other_dict = dict(other_dict) # also works with ConfigParser sections
@@ -468,13 +576,13 @@
del other_dict[setting]
self._update_loose(other_dict)
- def copy(self):
+ def copy(self) -> Values:
"""Return a shallow copy of `self`."""
with warnings.catch_warnings():
warnings.filterwarnings('ignore', category=DeprecationWarning)
return self.__class__(defaults=self.__dict__)
- def setdefault(self, name, default):
+ def setdefault(self, name: str, default: Any) -> Any:
"""Return ``self.name`` or ``default``.
If ``self.name`` is unset, set ``self.name = default``.
@@ -492,13 +600,18 @@
ATTRS = optparse.Option.ATTRS + ['validator', 'overrides']
- def __init__(self, *args, **kwargs):
+ validator: _OptionValidator
+ overrides: str | None
+
+ def __init__(self, *args: str | None, **kwargs: Any) -> None:
warnings.warn('The frontend.Option class will be removed '
'in Docutils 0.21 or later.',
DeprecationWarning, stacklevel=2)
super().__init__(*args, **kwargs)
- def process(self, opt, value, values, parser):
+ def process(
+ self, opt: str, value: Any, values: Values, parser: OptionParser,
+ ) -> int:
"""
Call the validator function on applicable settings and
evaluate the 'overrides' option.
@@ -537,7 +650,7 @@
Will be replaced by a subclass of `argparse.ArgumentParser`.
"""
- standard_config_files = [
+ standard_config_files: ClassVar[list[str]] = [
'/etc/docutils.conf', # system-wide
'./docutils.conf', # project-specific
'~/.docutils'] # user-specific
@@ -546,21 +659,29 @@
Filenames will be tilde-expanded later. Later files override earlier ones.
"""
- threshold_choices = 'info 1 warning 2 error 3 severe 4 none 5'.split()
+ threshold_choices: ClassVar[list[str]] = [
+ 'info', '1', 'warning', '2', 'error', '3', 'severe', '4', 'none', '5',
+ ]
"""Possible inputs for for --report and --halt threshold values."""
- thresholds = {'info': 1, 'warning': 2, 'error': 3, 'severe': 4, 'none': 5}
+ thresholds: ClassVar[dict[str, int]] = {
+ 'info': 1, 'warning': 2, 'error': 3, 'severe': 4, 'none': 5,
+ }
"""Lookup table for --report and --halt threshold values."""
- booleans = {'1': True, 'on': True, 'yes': True, 'true': True, '0': False,
- 'off': False, 'no': False, 'false': False, '': False}
+ booleans: ClassVar[dict[str, bool]] = {
+ '1': True, 'on': True, 'yes': True, 'true': True,
+ '0': False, 'off': False, 'no': False, 'false': False, '': False,
+ }
"""Lookup table for boolean configuration file settings."""
- default_error_encoding = (getattr(sys.stderr, 'encoding', None)
- or io._locale_encoding # noqa
- or 'ascii')
+ default_error_encoding: ClassVar[str] = (
+ getattr(sys.stderr, 'encoding', None)
+ or io._locale_encoding # noqa
+ or 'ascii'
+ )
- default_error_encoding_error_handler = 'backslashreplace'
+ default_error_encoding_error_handler: ClassVar[str] = 'backslashreplace'
settings_spec = (
'General Docutils Options',
@@ -748,17 +869,26 @@
See https://docutils.sourceforge.io/docs/user/config.html#internal-settings
"""
+ relative_path_settings: tuple[str, ...] = () # will be modified
+
config_section = 'general'
- version_template = ('%%prog (Docutils %s%s, Python %s, on %s)'
- % (docutils.__version__,
- docutils.__version_details__
- and ' [%s]'%docutils.__version_details__ or '',
- sys.version.split()[0], sys.platform))
+ version_template: ClassVar[str] = '%%prog (Docutils %s%s, Python %s, on %s)' % ( # NoQA: E501
+ docutils.__version__,
+ (details := docutils.__version_details__) and f' [{details}]' or '',
+ sys.version.split()[0],
+ sys.platform,
+ )
"""Default version message."""
- def __init__(self, components=(), defaults=None, read_config_files=False,
- *args, **kwargs):
+ def __init__(
+ self,
+ components: Iterable[SettingsSpec] = (),
+ defaults: Mapping[str, Any] | None = None,
+ read_config_files: bool | None = False,
+ *args,
+ **kwargs,
+ ) -> None:
"""Set up OptionParser instance.
`components` is a list of Docutils components each containing a
@@ -766,24 +896,24 @@
`defaults` is a mapping of setting default overrides.
"""
- self.lists = {}
+ self.lists: dict[str, Literal[True]] = {}
"""Set of list-type settings."""
- self.config_files = []
+ self.config_files: list[str] = []
"""List of paths of applied configuration files."""
- self.relative_path_settings = ['warning_stream'] # will be modified
+ self.relative_path_settings = ('warning_stream',) # will be modified
warnings.warn('The frontend.OptionParser class will be replaced '
'by a subclass of argparse.ArgumentParser '
'in Docutils 0.21 or later.',
DeprecationWarning, stacklevel=2)
- super().__init__(option_class=Option, add_help_option=None,
+ super().__init__(option_class=Option, add_help_option=False,
formatter=optparse.TitledHelpFormatter(width=78),
*args, **kwargs)
if not self.version:
self.version = self.version_template
- self.components = (self, *components)
+ self.components: tuple[SettingsSpec, ...] = (self, *components)
self.populate_from_components(self.components)
self.defaults.update(defaults or {})
if read_config_files and not self.defaults['_disable_config']:
@@ -790,10 +920,12 @@
try:
config_settings = self.get_standard_config_settings()
except ValueError as err:
- self.error(err)
+ self.error(str(err))
self.defaults.update(config_settings.__dict__)
- def populate_from_components(self, components):
+ def populate_from_components(
+ self, components: Iterable[SettingsSpec],
+ ) -> None:
"""Collect settings specification from components.
For each component, populate from the `SettingsSpec.settings_spec`
@@ -805,8 +937,7 @@
if component is None:
continue
settings_spec = component.settings_spec
- self.relative_path_settings.extend(
- component.relative_path_settings)
+ self.relative_path_settings += component.relative_path_settings
for i in range(0, len(settings_spec), 3):
title, description, option_spec = settings_spec[i:i+3]
if title:
@@ -826,7 +957,7 @@
self.defaults.update(component.settings_default_overrides)
@classmethod
- def get_standard_config_files(cls):
+ def get_standard_config_files(cls) -> Sequence[str | os.PathLike[str]]:
"""Return list of config files, from environment or standard."""
if 'DOCUTILSCONFIG' in os.environ:
config_files = os.environ['DOCUTILSCONFIG'].split(os.pathsep)
@@ -834,7 +965,7 @@
config_files = cls.standard_config_files
return [os.path.expanduser(f) for f in config_files if f.strip()]
- def get_standard_config_settings(self):
+ def get_standard_config_settings(self) -> Values:
with warnings.catch_warnings():
warnings.filterwarnings('ignore', category=DeprecationWarning)
settings = Values()
@@ -842,7 +973,7 @@
settings.update(self.get_config_file_settings(filename), self)
return settings
- def get_config_file_settings(self, config_file):
+ def get_config_file_settings(self, config_file: str) -> dict[str, Any]:
"""Returns a dictionary containing appropriate config file settings."""
config_parser = ConfigParser()
# parse config file, add filename if found and successfully read.
@@ -862,18 +993,18 @@
if config_parser.has_section(section):
settings.update(config_parser[section], self)
make_paths_absolute(settings.__dict__,
- self.relative_path_settings,
+ list(self.relative_path_settings),
os.path.dirname(config_file))
return settings.__dict__
- def check_values(self, values, args):
+ def check_values(self, values: Values, args: list[str]) -> Values:
"""Store positional arguments as runtime settings."""
values._source, values._destination = self.check_args(args)
- make_paths_absolute(values.__dict__, self.relative_path_settings)
+ make_paths_absolute(values.__dict__, list(self.relative_path_settings))
values._config_files = self.config_files
return values
- def check_args(self, args):
+ def check_args(self, args: list[str]) -> tuple[str | None, str | None]:
source = destination = None
if args:
source = args.pop(0)
@@ -890,7 +1021,7 @@
'destination. It will clobber the source file.')
return source, destination
- def set_defaults_from_dict(self, defaults):
+ def set_defaults_from_dict(self, defaults: dict[str, Any]) -> None:
# deprecated, will be removed
warnings.warn('OptionParser.set_defaults_from_dict() will be removed '
'in Docutils 0.22 or with the switch to ArgumentParser.',
@@ -897,7 +1028,7 @@
DeprecationWarning, stacklevel=2)
self.defaults.update(defaults)
- def get_default_values(self):
+ def get_default_values(self) -> Values:
"""Needed to get custom `Values` instances."""
with warnings.catch_warnings():
warnings.filterwarnings('ignore', category=DeprecationWarning)
@@ -905,7 +1036,7 @@
defaults._config_files = self.config_files
return defaults
- def get_option_by_dest(self, dest):
+ def get_option_by_dest(self, dest: str) -> Option:
"""
Get an option by its dest.
@@ -935,7 +1066,7 @@
This class is provisional and will change in future versions.
"""
- old_settings = {
+ old_settings: ClassVar[dict[str, tuple[str, str]]] = {
'pep_stylesheet': ('pep_html writer', 'stylesheet'),
'pep_stylesheet_path': ('pep_html writer', 'stylesheet_path'),
'pep_template': ('pep_html writer', 'template')}
@@ -943,7 +1074,7 @@
`handle_old_config`, to convert settings from the old [options] section.
"""
- old_warning = (
+ old_warning: ClassVar[str] = (
'The "[option]" section is deprecated.\n'
'Support for old-format configuration files will be removed in '
'Docutils 2.0. Please revise your configuration files. '
@@ -950,12 +1081,16 @@
'See <https://docutils.sourceforge.io/docs/user/config.html>, '
'section "Old-Format Configuration Files".')
- not_utf8_error = """\
+ not_utf8_error: ClassVar[str] = """\
Unable to read configuration file "%s": content not encoded as UTF-8.
Skipping "%s" configuration file.
"""
- def read(self, filenames, option_parser=None):
+ def read(
+ self,
+ filenames: str | Sequence[str],
+ option_parser: OptionParser | None = None,
+ ) -> list[str]:
# Currently, if a `docutils.frontend.OptionParser` instance is
# supplied, setting values are validated.
if option_parser is not None:
@@ -979,7 +1114,7 @@
self.validate_settings(filename, option_parser)
return read_ok
- def handle_old_config(self, filename):
+ def handle_old_config(self, filename: str) -> None:
warnings.warn_explicit(self.old_warning, ConfigDeprecationWarning,
filename, 0)
options = self.get_section('options')
@@ -997,7 +1132,9 @@
self.set(section, setting, value)
self.remove_section('options')
- def validate_settings(self, filename, option_parser):
+ def validate_settings(
+ self, filename: str, option_parser: OptionParser,
+ ) -> None:
"""
Call the validator function and implement overrides on all applicable
settings.
@@ -1023,7 +1160,7 @@
if option.overrides:
self.set(section, option.overrides, None)
- def optionxform(self, optionstr):
+ def optionxform(self, optionstr: str) -> str:
"""
Lowercase and transform '-' to '_'.
@@ -1031,7 +1168,7 @@
"""
return optionstr.lower().replace('-', '_')
- def get_section(self, section):
+ def get_section(self, section: str) -> dict[str, str]:
"""
Return a given section as a dictionary.
@@ -1053,7 +1190,7 @@
"""Warning for deprecated configuration file features."""
-def get_default_settings(*components):
+def get_default_settings(*components: SettingsSpec) -> Values:
"""Return default runtime settings for `components`.
Return a `frontend.Values` instance with defaults for generic Docutils
Modified: trunk/docutils/test/test_settings.py
===================================================================
--- trunk/docutils/test/test_settings.py 2024-07-31 10:44:49 UTC (rev 9804)
+++ trunk/docutils/test/test_settings.py 2024-07-31 12:59:29 UTC (rev 9805)
@@ -332,12 +332,12 @@
self.assertEqual(frontend.validate_comma_separated_list(v), result)
def test_validate_math_output(self):
- tests = (('', []),
- ('LaTeX ', ['latex', '']),
- ('MathML', ['mathml', '']),
- ('MathML PanDoc', ['mathml', 'pandoc']),
- ('HTML math.css, X.css', ['html', 'math.css, X.css']),
- ('MathJax /MathJax.js', ['mathjax', '/MathJax.js']),
+ tests = (('', ()),
+ ('LaTeX ', ('latex', '')),
+ ('MathML', ('mathml', '')),
+ ('MathML PanDoc', ('mathml', 'pandoc')),
+ ('HTML math.css, X.css', ('html', 'math.css, X.css')),
+ ('MathJax /MathJax.js', ('mathjax', '/MathJax.js')),
)
for v, result in tests:
self.assertEqual(frontend.validate_math_output(v), result)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <gr...@us...> - 2024-08-01 10:46:41
|
Revision: 9812
http://sourceforge.net/p/docutils/code/9812
Author: grubert
Date: 2024-08-01 10:46:38 +0000 (Thu, 01 Aug 2024)
Log Message:
-----------
add some tests for UR/UE
Modified Paths:
--------------
trunk/docutils/HISTORY.txt
trunk/docutils/test/test_writers/test_manpage.py
Modified: trunk/docutils/HISTORY.txt
===================================================================
--- trunk/docutils/HISTORY.txt 2024-08-01 07:32:03 UTC (rev 9811)
+++ trunk/docutils/HISTORY.txt 2024-08-01 10:46:38 UTC (rev 9812)
@@ -156,6 +156,8 @@
docutils version in header
- Stop converting text to full capitals (bug #481).
- Add module function insert_URI_breakpoints.
+ - Add command line option ``--use-reference-macros`` to enable usage of man
+ macros .UR/.UE.
* docutils/writers/null.py
Modified: trunk/docutils/test/test_writers/test_manpage.py
===================================================================
--- trunk/docutils/test/test_writers/test_manpage.py 2024-08-01 07:32:03 UTC (rev 9811)
+++ trunk/docutils/test/test_writers/test_manpage.py 2024-08-01 10:46:38 UTC (rev 9812)
@@ -57,7 +57,22 @@
}).decode()
self.assertEqual(case_expected, output)
+ def test_reference_macros(self):
+ writer = 'manpage'
+ for name, cases in totest_refs.items():
+ for casenum, (case_input, case_expected) in enumerate(cases):
+ with self.subTest(id=f'totest_refs[{name!r}][{casenum}]'):
+ output = publish_string(
+ source=case_input,
+ writer=writer,
+ settings_overrides={
+ '_disable_config': True,
+ 'strict_visitor': True,
+ 'use_reference_macros': True,
+ }).decode()
+ self.assertEqual(case_expected, output)
+
document_start = r""".\" Man page generated from reStructuredText by manpage writer
.\" from docutils 0.22b.dev.
.
@@ -92,6 +107,60 @@
..
"""
+totest_refs = {}
+
+totest_refs['ext hyperlink'] = [
+ [r"""External hyperlinks, like Python_.
+
+.. _Python: https://www.python.org/
+""",
+ document_start + indend_macros + """.TH "" "" "" ""
+.SH Name
+ \\- \n\
+External hyperlinks, like
+.UR https://www.python.org/
+Python
+.UE
+\&.
+.\\" End of generated man page.
+"""],
+ ]
+
+totest_refs['emb hyperlink'] = [
+ [r"""embedded External hyperlinks, like `Python
+<https://www.python.org/>`_.
+""",
+ document_start + indend_macros + """.TH "" "" "" ""
+.SH Name
+ \\- \n\
+embedded External hyperlinks, like \n\
+.UR https://www.python.org/
+Python
+.UE
+\&.
+.\\" End of generated man page.
+"""],
+ ]
+
+totest_refs['email'] = [
+ [r"""`Write to me`_ with your questions.
+
+.. _Write to me: jd...@ex...
+
+whatever.""",
+ document_start + indend_macros + """.TH "" "" "" ""
+.SH Name
+ \\- \n\
+.UR mailto:jd...@ex...
+Write to me
+.UE
+ with your questions.
+.sp
+whatever.
+.\\" End of generated man page.
+"""],
+ ]
+
totest = {}
totest['blank'] = [
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <aa-...@us...> - 2024-08-01 14:27:57
|
Revision: 9816
http://sourceforge.net/p/docutils/code/9816
Author: aa-turner
Date: 2024-08-01 14:27:54 +0000 (Thu, 01 Aug 2024)
Log Message:
-----------
Fix tests with Python 3.9
Modified Paths:
--------------
trunk/docutils/docutils/nodes.py
trunk/docutils/tools/dev/unicode2rstsubs.py
Modified: trunk/docutils/docutils/nodes.py
===================================================================
--- trunk/docutils/docutils/nodes.py 2024-08-01 14:03:04 UTC (rev 9815)
+++ trunk/docutils/docutils/nodes.py 2024-08-01 14:27:54 UTC (rev 9816)
@@ -1733,7 +1733,7 @@
# recursive content model, see below
-section.content_model: Final = (
+section.content_model = (
# (title, subtitle?, %structure.model;)
(title, '.'),
(subtitle, '?'),
@@ -2382,7 +2382,7 @@
# recursive content model: (line | line_block)+
-line_block.content_model: Final = (((line, line_block), '+'),)
+line_block.content_model = (((line, line_block), '+'),)
# Admonitions
Modified: trunk/docutils/tools/dev/unicode2rstsubs.py
===================================================================
--- trunk/docutils/tools/dev/unicode2rstsubs.py 2024-08-01 14:03:04 UTC (rev 9815)
+++ trunk/docutils/tools/dev/unicode2rstsubs.py 2024-08-01 14:27:54 UTC (rev 9816)
@@ -24,11 +24,11 @@
import os
import re
import sys
-from typing import TYPE_CHECKING, TextIO
+from typing import TYPE_CHECKING
from xml.parsers.expat import ParserCreate
if TYPE_CHECKING:
- from typing import BinaryIO, NoReturn
+ from typing import BinaryIO, NoReturn, TextIO
from xml.parsers.expat import XMLParserType
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <aa-...@us...> - 2024-08-01 19:29:41
|
Revision: 9820
http://sourceforge.net/p/docutils/code/9820
Author: aa-turner
Date: 2024-08-01 19:29:38 +0000 (Thu, 01 Aug 2024)
Log Message:
-----------
Fix test_fallback_{utf8,no_utf8}
Modified Paths:
--------------
trunk/docutils/docutils/io.py
trunk/docutils/test/test_io.py
Modified: trunk/docutils/docutils/io.py
===================================================================
--- trunk/docutils/docutils/io.py 2024-08-01 18:42:09 UTC (rev 9819)
+++ trunk/docutils/docutils/io.py 2024-08-01 19:29:38 UTC (rev 9820)
@@ -160,7 +160,10 @@
# data that *IS* UTF-8:
encoding_candidates = ['utf-8']
# If UTF-8 fails, fall back to the locale's preferred encoding:
- fallback = locale.getpreferredencoding(do_setlocale=False)
+ if sys.version_info[:2] >= (3, 11):
+ fallback = locale.getencoding()
+ else:
+ fallback = locale.getpreferredencoding(do_setlocale=False)
if fallback and fallback.lower() != 'utf-8':
encoding_candidates.append(fallback)
for enc in encoding_candidates:
Modified: trunk/docutils/test/test_io.py
===================================================================
--- trunk/docutils/test/test_io.py 2024-08-01 18:42:09 UTC (rev 9819)
+++ trunk/docutils/test/test_io.py 2024-08-01 19:29:38 UTC (rev 9820)
@@ -42,13 +42,6 @@
preferredencoding = codecs.lookup(
locale.getpreferredencoding(do_setlocale=False)).name
-if preferredencoding in {'cp1252', 'iso8859-1'}:
- expected_failure_on_non_utf8 = unittest.expectedFailure
-else:
- def expected_failure_on_non_utf8(test_item):
- return test_item
-
-
# Stub: Buffer with 'strict' auto-conversion of input to byte string:
class BBuf(BytesIO):
def write(self, data):
@@ -311,13 +304,14 @@
def test_fallback_utf8(self):
"""Try 'utf-8', if encoding is not specified in the source."""
- source = du_io.FileInput(
- source_path=os.path.join(DATA_ROOT, 'utf8.txt'))
+ with warnings.catch_warnings():
+ if SUPPRESS_ENCODING_WARNING:
+ warnings.filterwarnings('ignore', category=EncodingWarning)
+ source = du_io.FileInput(
+ source_path=os.path.join(DATA_ROOT, 'utf8.txt'),
+ encoding=None)
self.assertEqual('Grüße\n', source.read())
- # Failing on non-UTF-8 locales (with UTF-8 mode disabled):
- # see https://sourceforge.net/p/docutils/bugs/490/#43b7
- @expected_failure_on_non_utf8
@unittest.skipIf(preferredencoding in (None, 'ascii', 'utf-8'),
'locale encoding not set or UTF-8')
def test_fallback_no_utf8(self):
@@ -325,8 +319,12 @@
# use the locale's preferred encoding (if not None).
# Provisional: the default will become 'utf-8'
# (without auto-detection and fallback) in Docutils 0.22.
- source = du_io.FileInput(
- source_path=os.path.join(DATA_ROOT, 'latin1.txt'))
+ with warnings.catch_warnings():
+ if SUPPRESS_ENCODING_WARNING:
+ warnings.filterwarnings('ignore', category=EncodingWarning)
+ source = du_io.FileInput(
+ source_path=os.path.join(DATA_ROOT, 'latin1.txt'),
+ encoding=None)
data = source.read()
successful_encoding = codecs.lookup(source.successful_encoding).name
self.assertEqual(preferredencoding, successful_encoding)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <aa-...@us...> - 2024-08-01 20:47:14
|
Revision: 9829
http://sourceforge.net/p/docutils/code/9829
Author: aa-turner
Date: 2024-08-01 20:47:11 +0000 (Thu, 01 Aug 2024)
Log Message:
-----------
Enable the pygrep-hooks linter in Ruff
Modified Paths:
--------------
trunk/docutils/.ruff.toml
trunk/docutils/docutils/__init__.py
trunk/docutils/docutils/frontend.py
trunk/docutils/docutils/io.py
trunk/docutils/docutils/nodes.py
trunk/docutils/docutils/parsers/recommonmark_wrapper.py
trunk/docutils/docutils/statemachine.py
trunk/docutils/docutils/utils/smartquotes.py
trunk/docutils/test/test_language.py
trunk/docutils/test/test_parsers/test_rst/test_directives/test_date.py
Modified: trunk/docutils/.ruff.toml
===================================================================
--- trunk/docutils/.ruff.toml 2024-08-01 20:41:32 UTC (rev 9828)
+++ trunk/docutils/.ruff.toml 2024-08-01 20:47:11 UTC (rev 9829)
@@ -14,6 +14,7 @@
"INP", # flake8-no-pep420
"INT", # flake8-gettext
"LOG", # flake8-logging
+ "PGH", # pygrep-hooks
"W", # pycodestyle
]
ignore = [
Modified: trunk/docutils/docutils/__init__.py
===================================================================
--- trunk/docutils/docutils/__init__.py 2024-08-01 20:41:32 UTC (rev 9828)
+++ trunk/docutils/docutils/__init__.py 2024-08-01 20:47:11 UTC (rev 9829)
@@ -125,7 +125,7 @@
raise ValueError('releaselevel "final" must not be used '
'with development versions (leads to wrong '
'version ordering of the related __version__')
- # cf. https://peps.python.org/pep-0440/#summary-of-permitted-suffixes-and-relative-ordering # noqa
+ # cf. https://peps.python.org/pep-0440/#summary-of-permitted-suffixes-and-relative-ordering # NoQA: E501
if serial != 0:
raise ValueError('"serial" must be 0 for final releases')
Modified: trunk/docutils/docutils/frontend.py
===================================================================
--- trunk/docutils/docutils/frontend.py 2024-08-01 20:41:32 UTC (rev 9828)
+++ trunk/docutils/docutils/frontend.py 2024-08-01 20:47:11 UTC (rev 9829)
@@ -677,7 +677,7 @@
default_error_encoding: ClassVar[str] = (
getattr(sys.stderr, 'encoding', None)
- or io._locale_encoding # noqa
+ or io._locale_encoding
or 'ascii'
)
Modified: trunk/docutils/docutils/io.py
===================================================================
--- trunk/docutils/docutils/io.py 2024-08-01 20:41:32 UTC (rev 9828)
+++ trunk/docutils/docutils/io.py 2024-08-01 20:47:11 UTC (rev 9829)
@@ -39,7 +39,8 @@
_locale_encoding: str | None = (
locale.getlocale()[1] or locale.getdefaultlocale()[1]
).lower()
-except: # noqa any other problems determining the locale -> use None
+except: # NoQA: E722
+ # any other problems determining the locale -> use None
_locale_encoding = None
try:
codecs.lookup(_locale_encoding)
Modified: trunk/docutils/docutils/nodes.py
===================================================================
--- trunk/docutils/docutils/nodes.py 2024-08-01 20:41:32 UTC (rev 9828)
+++ trunk/docutils/docutils/nodes.py 2024-08-01 20:47:11 UTC (rev 9829)
@@ -2589,7 +2589,7 @@
children = (p,) + children
try:
Element.__init__(self, rawsource, *children, **attributes)
- except: # noqa catchall
+ except: # NoQA: E722
print('system_message: children=%r' % (children,))
raise
Modified: trunk/docutils/docutils/parsers/recommonmark_wrapper.py
===================================================================
--- trunk/docutils/docutils/parsers/recommonmark_wrapper.py 2024-08-01 20:41:32 UTC (rev 9828)
+++ trunk/docutils/docutils/parsers/recommonmark_wrapper.py 2024-08-01 20:47:11 UTC (rev 9829)
@@ -35,7 +35,8 @@
import sys
import types
- class pending_xref(nodes.Inline, nodes.Element): ... # NoQA
+ class pending_xref(nodes.Inline, nodes.Element):
+ ...
sys.modules['sphinx'] = sphinx = types.ModuleType('sphinx')
sphinx.addnodes = addnodes = types.SimpleNamespace()
Modified: trunk/docutils/docutils/statemachine.py
===================================================================
--- trunk/docutils/docutils/statemachine.py 2024-08-01 20:41:32 UTC (rev 9828)
+++ trunk/docutils/docutils/statemachine.py 2024-08-01 20:47:11 UTC (rev 9829)
@@ -264,7 +264,7 @@
else:
transitions = None
state = self.get_state(next_state)
- except: # noqa catchall
+ except: # NoQA: E722
if self.debug:
self.error()
raise
@@ -674,7 +674,7 @@
try:
del self.transitions[name]
self.transition_order.remove(name)
- except: # noqa catchall
+ except: # NoQA: E722
raise UnknownTransitionError(name)
def make_transition(self, name, next_state=None):
@@ -1103,13 +1103,24 @@
def __repr__(self) -> str:
return f'{self.__class__.__name__}({self.data}, items={self.items})'
- def __lt__(self, other): return self.data < self.__cast(other) # noqa
- def __le__(self, other): return self.data <= self.__cast(other) # noqa
- def __eq__(self, other): return self.data == self.__cast(other) # noqa
- def __ne__(self, other): return self.data != self.__cast(other) # noqa
- def __gt__(self, other): return self.data > self.__cast(other) # noqa
- def __ge__(self, other): return self.data >= self.__cast(other) # noqa
+ def __lt__(self, other):
+ return self.data < self.__cast(other)
+ def __le__(self, other):
+ return self.data <= self.__cast(other)
+
+ def __eq__(self, other):
+ return self.data == self.__cast(other)
+
+ def __ne__(self, other):
+ return self.data != self.__cast(other)
+
+ def __gt__(self, other):
+ return self.data > self.__cast(other)
+
+ def __ge__(self, other):
+ return self.data >= self.__cast(other)
+
def __cast(self, other):
if isinstance(other, ViewList):
return other.data
Modified: trunk/docutils/docutils/utils/smartquotes.py
===================================================================
--- trunk/docutils/docutils/utils/smartquotes.py 2024-08-01 20:41:32 UTC (rev 9828)
+++ trunk/docutils/docutils/utils/smartquotes.py 2024-08-01 20:47:11 UTC (rev 9829)
@@ -911,7 +911,7 @@
try:
locale.setlocale(locale.LC_ALL, '') # set to user defaults
defaultlanguage = locale.getlocale()[0]
- except: # noqa catchall
+ except: # NoQA: E722
defaultlanguage = 'en'
# Normalize and drop unsupported subtags:
Modified: trunk/docutils/test/test_language.py
===================================================================
--- trunk/docutils/test/test_language.py 2024-08-01 20:41:32 UTC (rev 9828)
+++ trunk/docutils/test/test_language.py 2024-08-01 20:47:11 UTC (rev 9829)
@@ -26,8 +26,8 @@
from docutils import frontend, languages, utils
from docutils.parsers.rst import languages as rst_languages
-from docutils.parsers.rst.directives import _directive_registry # NoQA
-from docutils.parsers.rst.roles import _role_registry # NoQA
+from docutils.parsers.rst.directives import _directive_registry
+from docutils.parsers.rst.roles import _role_registry
LANGUAGE_MODULE_PATTERN = re.compile(r'^([a-z]{2,3}(_[a-z]{2,8})*)\.py$')
REPORTER = utils.new_reporter('', frontend.get_default_settings())
Modified: trunk/docutils/test/test_parsers/test_rst/test_directives/test_date.py
===================================================================
--- trunk/docutils/test/test_parsers/test_rst/test_directives/test_date.py 2024-08-01 20:41:32 UTC (rev 9828)
+++ trunk/docutils/test/test_parsers/test_rst/test_directives/test_date.py 2024-08-01 20:47:11 UTC (rev 9829)
@@ -18,7 +18,7 @@
# so we import the local `docutils` package.
sys.path.insert(0, str(Path(__file__).resolve().parents[4]))
-from docutils.io import _locale_encoding # noqa
+from docutils.io import _locale_encoding
from docutils.frontend import get_default_settings
from docutils.parsers.rst import Parser
from docutils.utils import new_document
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <aa-...@us...> - 2024-08-01 20:52:02
|
Revision: 9830
http://sourceforge.net/p/docutils/code/9830
Author: aa-turner
Date: 2024-08-01 20:51:58 +0000 (Thu, 01 Aug 2024)
Log Message:
-----------
Enable the flake8-pie linter in Ruff
Modified Paths:
--------------
trunk/docutils/.ruff.toml
trunk/docutils/docutils/io.py
trunk/docutils/docutils/parsers/recommonmark_wrapper.py
trunk/docutils/docutils/parsers/rst/states.py
trunk/docutils/docutils/statemachine.py
trunk/docutils/docutils/utils/math/math2html.py
trunk/docutils/docutils/utils/math/tex2mathml_extern.py
Modified: trunk/docutils/.ruff.toml
===================================================================
--- trunk/docutils/.ruff.toml 2024-08-01 20:47:11 UTC (rev 9829)
+++ trunk/docutils/.ruff.toml 2024-08-01 20:51:58 UTC (rev 9830)
@@ -15,6 +15,7 @@
"INT", # flake8-gettext
"LOG", # flake8-logging
"PGH", # pygrep-hooks
+ "PIE", # flake8-pie
"W", # pycodestyle
]
ignore = [
Modified: trunk/docutils/docutils/io.py
===================================================================
--- trunk/docutils/docutils/io.py 2024-08-01 20:47:11 UTC (rev 9829)
+++ trunk/docutils/docutils/io.py 2024-08-01 20:51:58 UTC (rev 9830)
@@ -686,7 +686,6 @@
def write(self, data: str | bytes) -> None:
"""Do nothing, return None."""
- pass
class DocTreeInput(Input):
Modified: trunk/docutils/docutils/parsers/recommonmark_wrapper.py
===================================================================
--- trunk/docutils/docutils/parsers/recommonmark_wrapper.py 2024-08-01 20:47:11 UTC (rev 9829)
+++ trunk/docutils/docutils/parsers/recommonmark_wrapper.py 2024-08-01 20:51:58 UTC (rev 9830)
@@ -163,7 +163,6 @@
cf. https://github.com/readthedocs/recommonmark/issues/177
"""
- pass
# Overwrite parent method with version that
# doesn't pass deprecated `rawsource` argument to nodes.Text:
Modified: trunk/docutils/docutils/parsers/rst/states.py
===================================================================
--- trunk/docutils/docutils/parsers/rst/states.py 2024-08-01 20:47:11 UTC (rev 9829)
+++ trunk/docutils/docutils/parsers/rst/states.py 2024-08-01 20:51:58 UTC (rev 9830)
@@ -1409,8 +1409,7 @@
if result:
next_enumerator, auto_enumerator = result
try:
- if (next_line.startswith(next_enumerator)
- or next_line.startswith(auto_enumerator)):
+ if next_line.startswith((next_enumerator, auto_enumerator)):
return 1
except TypeError:
pass
Modified: trunk/docutils/docutils/statemachine.py
===================================================================
--- trunk/docutils/docutils/statemachine.py 2024-08-01 20:47:11 UTC (rev 9829)
+++ trunk/docutils/docutils/statemachine.py 2024-08-01 20:51:58 UTC (rev 9830)
@@ -620,7 +620,6 @@
Initialize this `State` before running the state machine; called from
`self.state_machine.run()`.
"""
- pass
def unlink(self) -> None:
"""Remove circular references to objects no longer required."""
@@ -1042,12 +1041,10 @@
class SearchStateMachine(_SearchOverride, StateMachine):
"""`StateMachine` which uses `re.search()` instead of `re.match()`."""
- pass
class SearchStateMachineWS(_SearchOverride, StateMachineWS):
"""`StateMachineWS` which uses `re.search()` instead of `re.match()`."""
- pass
class ViewList:
Modified: trunk/docutils/docutils/utils/math/math2html.py
===================================================================
--- trunk/docutils/docutils/utils/math/math2html.py 2024-08-01 20:47:11 UTC (rev 9829)
+++ trunk/docutils/docutils/utils/math/math2html.py 2024-08-01 20:51:58 UTC (rev 9830)
@@ -1320,7 +1320,6 @@
def process(self) -> None:
"Process contents"
- pass
def gethtml(self):
"Get the resulting HTML"
@@ -2132,7 +2131,7 @@
bit = self.parsewithcommand(command, pos)
if bit:
return bit
- if command.startswith('\\up') or command.startswith('\\Up'):
+ if command.startswith(('\\up', '\\Up')):
upgreek = self.parseupgreek(command, pos)
if upgreek:
return upgreek
Modified: trunk/docutils/docutils/utils/math/tex2mathml_extern.py
===================================================================
--- trunk/docutils/docutils/utils/math/tex2mathml_extern.py 2024-08-01 20:47:11 UTC (rev 9829)
+++ trunk/docutils/docutils/utils/math/tex2mathml_extern.py 2024-08-01 20:51:58 UTC (rev 9830)
@@ -107,10 +107,10 @@
result1 = subprocess.run(args1, input=math_code,
capture_output=True, text=True)
if result1.stderr:
- result1.stderr = '\n'.join(line for line in result1.stderr.splitlines()
- if line.startswith('Error:')
- or line.startswith('Warning:')
- or line.startswith('Fatal:'))
+ result1.stderr = '\n'.join(
+ line for line in result1.stderr.splitlines()
+ if line.startswith(('Error:', 'Warning:', 'Fatal:'))
+ )
_check_result(result1)
args2 = ['latexmlpost',
@@ -142,10 +142,10 @@
_msg_source = result2.stdout # latexmlpost reports errors in output
else:
_msg_source = result2.stderr # just in case
- result2.stderr = '\n'.join(line for line in _msg_source.splitlines()
- if line.startswith('Error:')
- or line.startswith('Warning:')
- or line.startswith('Fatal:'))
+ result2.stderr = '\n'.join(
+ line for line in _msg_source.splitlines()
+ if line.startswith(('Error:', 'Warning:', 'Fatal:'))
+ )
_check_result(result2)
return result2.stdout
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <aa-...@us...> - 2024-08-01 20:55:42
|
Revision: 9832
http://sourceforge.net/p/docutils/code/9832
Author: aa-turner
Date: 2024-08-01 20:55:40 +0000 (Thu, 01 Aug 2024)
Log Message:
-----------
Enable the flake8-raise linter in Ruff
Modified Paths:
--------------
trunk/docutils/.ruff.toml
trunk/docutils/docutils/writers/odf_odt/__init__.py
Modified: trunk/docutils/.ruff.toml
===================================================================
--- trunk/docutils/.ruff.toml 2024-08-01 20:53:57 UTC (rev 9831)
+++ trunk/docutils/.ruff.toml 2024-08-01 20:55:40 UTC (rev 9832)
@@ -17,6 +17,7 @@
"PGH", # pygrep-hooks
"PIE", # flake8-pie
"PT", # flake8-pytest
+ "RSE", # flake8-raise
"W", # pycodestyle
]
ignore = [
Modified: trunk/docutils/docutils/writers/odf_odt/__init__.py
===================================================================
--- trunk/docutils/docutils/writers/odf_odt/__init__.py 2024-08-01 20:53:57 UTC (rev 9831)
+++ trunk/docutils/docutils/writers/odf_odt/__init__.py 2024-08-01 20:55:40 UTC (rev 9832)
@@ -1743,7 +1743,7 @@
self.list_level -= 1
def visit_caption(self, node):
- raise nodes.SkipChildren()
+ raise nodes.SkipChildren
def depart_caption(self, node) -> None:
pass
@@ -1802,7 +1802,7 @@
el = self.append_p('deflist-term-%d' % self.def_list_level)
el.text = node.astext()
self.set_current_element(el)
- raise nodes.SkipChildren()
+ raise nodes.SkipChildren
def depart_term(self, node) -> None:
self.set_to_parent()
@@ -2039,7 +2039,7 @@
})
el2.text = footnote_char
self.footnote_ref_dict[id] = el1
- raise nodes.SkipChildren()
+ raise nodes.SkipChildren
def depart_footnote_reference(self, node) -> None:
pass
@@ -2079,7 +2079,7 @@
def visit_label(self, node):
if isinstance(node.parent, docutils.nodes.footnote):
- raise nodes.SkipChildren()
+ raise nodes.SkipChildren
elif self.citation_id is not None:
el = self.append_p('textbody')
self.set_current_element(el)
@@ -2809,7 +2809,7 @@
el1 = SubElement(el, 'text:p', attrib={
'text:style-name': 'Table_20_Contents'})
el1.text = node.astext()
- raise nodes.SkipChildren()
+ raise nodes.SkipChildren
def depart_description(self, node) -> None:
pass
@@ -2864,7 +2864,7 @@
pass
else:
self.current_element.append(el1)
- raise nodes.SkipChildren()
+ raise nodes.SkipChildren
def depart_raw(self, node) -> None:
if self.in_header:
@@ -2949,7 +2949,7 @@
self.set_to_parent()
def visit_substitution_definition(self, node):
- raise nodes.SkipChildren()
+ raise nodes.SkipChildren
def depart_substitution_definition(self, node) -> None:
pass
@@ -3207,7 +3207,7 @@
el = self.append_child('text:span', attrib={
'text:style-name': self.rststyle('quotation')})
el.text = self.encode(node.astext())
- raise nodes.SkipChildren()
+ raise nodes.SkipChildren
def depart_title_reference(self, node) -> None:
pass
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <aa-...@us...> - 2024-08-01 21:19:12
|
Revision: 9833
http://sourceforge.net/p/docutils/code/9833
Author: aa-turner
Date: 2024-08-01 21:19:10 +0000 (Thu, 01 Aug 2024)
Log Message:
-----------
Enable the flake8-slots linter in Ruff
Modified Paths:
--------------
trunk/docutils/.ruff.toml
trunk/docutils/docutils/__init__.py
trunk/docutils/docutils/nodes.py
Modified: trunk/docutils/.ruff.toml
===================================================================
--- trunk/docutils/.ruff.toml 2024-08-01 20:55:40 UTC (rev 9832)
+++ trunk/docutils/.ruff.toml 2024-08-01 21:19:10 UTC (rev 9833)
@@ -18,6 +18,7 @@
"PIE", # flake8-pie
"PT", # flake8-pytest
"RSE", # flake8-raise
+ "SLOT", # flake8-slots
"W", # pycodestyle
]
ignore = [
Modified: trunk/docutils/docutils/__init__.py
===================================================================
--- trunk/docutils/docutils/__init__.py 2024-08-01 20:55:40 UTC (rev 9832)
+++ trunk/docutils/docutils/__init__.py 2024-08-01 21:19:10 UTC (rev 9833)
@@ -104,6 +104,8 @@
class VersionInfo(namedtuple('VersionInfo',
'major minor micro releaselevel serial release')):
+ __slots__ = ()
+
major: int
minor: int
micro: int
Modified: trunk/docutils/docutils/nodes.py
===================================================================
--- trunk/docutils/docutils/nodes.py 2024-08-01 20:55:40 UTC (rev 9832)
+++ trunk/docutils/docutils/nodes.py 2024-08-01 21:19:10 UTC (rev 9833)
@@ -392,7 +392,7 @@
return None
-class Text(Node, str):
+class Text(Node, str): # NoQA: SLOT000 (Node doesn't define __slots__)
"""
Instances are terminal nodes (leaves) containing text only; no child
nodes or attributes. Initialize by passing a string to the constructor.
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <aa-...@us...> - 2024-08-01 21:25:59
|
Revision: 9839
http://sourceforge.net/p/docutils/code/9839
Author: aa-turner
Date: 2024-08-01 21:25:56 +0000 (Thu, 01 Aug 2024)
Log Message:
-----------
Enable the flake8-comprehensions linter in Ruff
Modified Paths:
--------------
trunk/docutils/.ruff.toml
trunk/docutils/docutils/parsers/rst/directives/images.py
trunk/docutils/docutils/utils/__init__.py
trunk/docutils/docutils/utils/math/math2html.py
trunk/docutils/docutils/utils/smartquotes.py
trunk/docutils/test/test_viewlist.py
trunk/docutils/test/test_writers/test_latex2e.py
Modified: trunk/docutils/.ruff.toml
===================================================================
--- trunk/docutils/.ruff.toml 2024-08-01 21:23:58 UTC (rev 9838)
+++ trunk/docutils/.ruff.toml 2024-08-01 21:25:56 UTC (rev 9839)
@@ -5,6 +5,7 @@
[lint]
preview = true
select = [
+ "C4", # flake8-comprehensions
"E", # pycodestyle
"EXE", # flake8-executable
"DTZ", # flake8-datetimez
Modified: trunk/docutils/docutils/parsers/rst/directives/images.py
===================================================================
--- trunk/docutils/docutils/parsers/rst/directives/images.py 2024-08-01 21:23:58 UTC (rev 9838)
+++ trunk/docutils/docutils/parsers/rst/directives/images.py 2024-08-01 21:25:56 UTC (rev 9839)
@@ -81,7 +81,7 @@
if 'target' in self.options:
block = states.escape2null(
self.options['target']).splitlines()
- block = [line for line in block]
+ block = list(block)
target_type, data = self.state.parse_target(
block, self.block_text, self.lineno)
if target_type == 'refuri':
Modified: trunk/docutils/docutils/utils/__init__.py
===================================================================
--- trunk/docutils/docutils/utils/__init__.py 2024-08-01 21:23:58 UTC (rev 9838)
+++ trunk/docutils/docutils/utils/__init__.py 2024-08-01 21:25:56 UTC (rev 9839)
@@ -720,7 +720,7 @@
tag = tag.lower().replace('-', '_')
# split (except singletons, which mark the following tag as non-standard):
tag = re.sub(r'_([a-zA-Z0-9])_', r'_\1-', tag)
- subtags = [subtag for subtag in tag.split('_')]
+ subtags = list(tag.split('_'))
base_tag = (subtags.pop(0),)
# find all combinations of subtags
taglist = []
Modified: trunk/docutils/docutils/utils/math/math2html.py
===================================================================
--- trunk/docutils/docutils/utils/math/math2html.py 2024-08-01 21:23:58 UTC (rev 9838)
+++ trunk/docutils/docutils/utils/math/math2html.py 2024-08-01 21:25:56 UTC (rev 9839)
@@ -1316,7 +1316,7 @@
begin = None
def __init__(self) -> None:
- self.contents = list()
+ self.contents = []
def process(self) -> None:
"Process contents"
Modified: trunk/docutils/docutils/utils/smartquotes.py
===================================================================
--- trunk/docutils/docutils/utils/smartquotes.py 2024-08-01 21:23:58 UTC (rev 9838)
+++ trunk/docutils/docutils/utils/smartquotes.py 2024-08-01 21:25:56 UTC (rev 9839)
@@ -918,7 +918,7 @@
defaultlanguage = defaultlanguage.lower().replace('-', '_')
# split (except singletons, which mark the following tag as non-standard):
defaultlanguage = re.sub(r'_([a-zA-Z0-9])_', r'_\1-', defaultlanguage)
- _subtags = [subtag for subtag in defaultlanguage.split('_')]
+ _subtags = list(defaultlanguage.split('_'))
_basetag = _subtags.pop(0)
# find all combinations of subtags
for n in range(len(_subtags), 0, -1):
Modified: trunk/docutils/test/test_viewlist.py
===================================================================
--- trunk/docutils/test/test_viewlist.py 2024-08-01 21:23:58 UTC (rev 9838)
+++ trunk/docutils/test/test_viewlist.py 2024-08-01 21:25:56 UTC (rev 9839)
@@ -46,7 +46,7 @@
self.assertEqual(self.c, self.c_list)
self.assertEqual(len(self.a), len(self.a_list))
self.assertTrue('d' in self.a) # __contains__
- self.assertEqual([value for value in self.a], self.a_list)
+ self.assertEqual(list(self.a), self.a_list)
# get and set values
self.assertEqual(self.a[2], self.a_list[2])
a = self.a[:]
Modified: trunk/docutils/test/test_writers/test_latex2e.py
===================================================================
--- trunk/docutils/test/test_writers/test_latex2e.py 2024-08-01 21:23:58 UTC (rev 9838)
+++ trunk/docutils/test/test_writers/test_latex2e.py 2024-08-01 21:25:56 UTC (rev 9839)
@@ -121,24 +121,24 @@
\begin{document}
$titledata""")
-parts = dict(
-head_prefix=r"""\documentclass[a4paper]{article}
+parts = {
+'head_prefix': r"""\documentclass[a4paper]{article}
""",
-requirements=r"""\usepackage{ifthen}
+'requirements': r"""\usepackage{ifthen}
\usepackage[T1]{fontenc}
""",
-latex_preamble=r"""% PDF Standard Fonts
+'latex_preamble': r"""% PDF Standard Fonts
\usepackage{mathptmx} % Times
\usepackage[scaled=.90]{helvet}
\usepackage{courier}
""",
-longtable=r"""\usepackage{longtable,ltcaption,array}
+'longtable': r"""\usepackage{longtable,ltcaption,array}
\setlength{\extrarowheight}{2pt}
\newlength{\DUtablewidth} % internal use in tables
""",
-stylesheet='',
-fallbacks='',
-fallbacks_highlight=r"""
+'stylesheet': '',
+'fallbacks': '',
+'fallbacks_highlight': r"""
% basic code highlight:
\providecommand*\DUrolecomment[1]{\textcolor[rgb]{0.40,0.40,0.40}{#1}}
\providecommand*\DUroledeleted[1]{\textcolor[rgb]{0.40,0.40,0.40}{#1}}
@@ -154,7 +154,7 @@
\fi%
}
""",
-pdfsetup=r"""
+'pdfsetup': r"""
% hyperlinks:
\ifthenelse{\isundefined{\hypersetup}}{
\usepackage[colorlinks=true,linkcolor=blue,urlcolor=blue]{hyperref}
@@ -162,7 +162,7 @@
\urlstyle{same} % normal text font (alternatives: tt, rm, sf)
}{}
""",
-titledata='')
+'titledata': ''}
head = head_template.substitute(parts)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <aa-...@us...> - 2024-08-01 21:56:21
|
Revision: 9840
http://sourceforge.net/p/docutils/code/9840
Author: aa-turner
Date: 2024-08-01 21:56:03 +0000 (Thu, 01 Aug 2024)
Log Message:
-----------
Enable the flake8-builtins linter in Ruff
Modified Paths:
--------------
trunk/docutils/.ruff.toml
trunk/docutils/docutils/core.py
trunk/docutils/docutils/nodes.py
trunk/docutils/docutils/parsers/rst/directives/admonitions.py
trunk/docutils/docutils/parsers/rst/states.py
trunk/docutils/docutils/statemachine.py
trunk/docutils/docutils/transforms/peps.py
trunk/docutils/docutils/utils/math/math2html.py
trunk/docutils/docutils/writers/odf_odt/__init__.py
trunk/docutils/test/alltests.py
trunk/docutils/test/test_io.py
trunk/docutils/test/test_nodes.py
trunk/docutils/test/test_utils/test__init__.py
trunk/docutils/tools/dev/quicktest.py
trunk/docutils/tools/dev/unicode2rstsubs.py
Modified: trunk/docutils/.ruff.toml
===================================================================
--- trunk/docutils/.ruff.toml 2024-08-01 21:25:56 UTC (rev 9839)
+++ trunk/docutils/.ruff.toml 2024-08-01 21:56:03 UTC (rev 9840)
@@ -5,6 +5,7 @@
[lint]
preview = true
select = [
+ "A", # flake8-builtins
"C4", # flake8-comprehensions
"E", # pycodestyle
"EXE", # flake8-executable
@@ -77,6 +78,8 @@
# module with 3rd-party origin
"docutils/utils/math/math2html.py" = [
+ "A001", # 'type' is used very frequently
+ "A002", # 'type' is used very frequently
"E241",
"E501",
"E731",
@@ -169,3 +172,9 @@
"tools/dev/generate_punctuation_chars.py" = [
"E501",
]
+
+[lint.flake8-builtins]
+builtins-ignorelist = [
+ "format",
+ "id",
+]
Modified: trunk/docutils/docutils/core.py
===================================================================
--- trunk/docutils/docutils/core.py 2024-08-01 21:25:56 UTC (rev 9839)
+++ trunk/docutils/docutils/core.py 2024-08-01 21:56:03 UTC (rev 9840)
@@ -247,7 +247,7 @@
already set), run `self.reader` and then `self.writer`. Return
`self.writer`'s output.
"""
- exit = None
+ exit_ = None
try:
if self.settings is None:
self.process_command_line(
@@ -261,7 +261,7 @@
output = self.writer.write(self.document, self.destination)
self.writer.assemble_parts()
except SystemExit as error:
- exit = True
+ exit_ = True
exit_status = error.code
except Exception as error:
if not self.settings: # exception too early to report nicely
@@ -270,7 +270,7 @@
self.debugging_dumps()
raise
self.report_Exception(error)
- exit = True
+ exit_ = True
exit_status = 1
self.debugging_dumps()
if (enable_exit_status and self.document
@@ -277,7 +277,7 @@
and (self.document.reporter.max_level
>= self.settings.exit_status_level)):
sys.exit(self.document.reporter.max_level + 10)
- elif exit:
+ elif exit_:
sys.exit(exit_status)
return output
Modified: trunk/docutils/docutils/nodes.py
===================================================================
--- trunk/docutils/docutils/nodes.py 2024-08-01 21:25:56 UTC (rev 9839)
+++ trunk/docutils/docutils/nodes.py 2024-08-01 21:56:03 UTC (rev 9840)
@@ -1357,16 +1357,16 @@
) -> str:
# Return a str reporting a missing child or child of wrong category.
try:
- type = category.__name__
+ type_ = category.__name__
except AttributeError:
- type = '> or <'.join(c.__name__ for c in category)
+ type_ = '> or <'.join(c.__name__ for c in category)
msg = f'Element {self.starttag()} invalid:\n'
if child is None:
- return f'{msg} Missing child of type <{type}>.'
+ return f'{msg} Missing child of type <{type_}>.'
if isinstance(child, Text):
- return (f'{msg} Expecting child of type <{type}>, '
+ return (f'{msg} Expecting child of type <{type_}>, '
f'not text data "{child.astext()}".')
- return (f'{msg} Expecting child of type <{type}>, '
+ return (f'{msg} Expecting child of type <{type_}>, '
f'not {child.starttag()}.')
def check_position(self) -> None:
@@ -2172,7 +2172,7 @@
class revision(Bibliographic, TextElement): pass
class status(Bibliographic, TextElement): pass
class date(Bibliographic, TextElement): pass
-class copyright(Bibliographic, TextElement): pass
+class copyright(Bibliographic, TextElement): pass # NoQA: A001
class authors(Bibliographic, Element):
Modified: trunk/docutils/docutils/parsers/rst/directives/admonitions.py
===================================================================
--- trunk/docutils/docutils/parsers/rst/directives/admonitions.py 2024-08-01 21:25:56 UTC (rev 9839)
+++ trunk/docutils/docutils/parsers/rst/directives/admonitions.py 2024-08-01 21:56:03 UTC (rev 9840)
@@ -96,6 +96,6 @@
node_class = nodes.tip
-class Warning(BaseAdmonition):
+class Warning(BaseAdmonition): # NoQA: A001
node_class = nodes.warning
Modified: trunk/docutils/docutils/parsers/rst/states.py
===================================================================
--- trunk/docutils/docutils/parsers/rst/states.py 2024-08-01 21:25:56 UTC (rev 9839)
+++ trunk/docutils/docutils/parsers/rst/states.py 2024-08-01 21:56:03 UTC (rev 9840)
@@ -434,7 +434,7 @@
line=lineno)
-def build_regexp(definition, compile=True):
+def build_regexp(definition, compile_patterns=True):
"""
Build, compile and return a regular expression based on `definition`.
@@ -451,7 +451,7 @@
part_strings.append(part)
or_group = '|'.join(part_strings)
regexp = '%(prefix)s(?P<%(name)s>%(or_group)s)%(suffix)s' % locals()
- if compile:
+ if compile_patterns:
return re.compile(regexp)
else:
return regexp
Modified: trunk/docutils/docutils/statemachine.py
===================================================================
--- trunk/docutils/docutils/statemachine.py 2024-08-01 21:25:56 UTC (rev 9839)
+++ trunk/docutils/docutils/statemachine.py 2024-08-01 21:56:03 UTC (rev 9840)
@@ -477,8 +477,8 @@
def error(self) -> None:
"""Report error details."""
- type, value, module, line, function = _exception_data()
- print('%s: %s' % (type, value), file=sys.stderr)
+ type_name, value, module, line, function = _exception_data()
+ print('%s: %s' % (type_name, value), file=sys.stderr)
print('input line %s' % (self.abs_line_number()), file=sys.stderr)
print('module %s, line %s, function %s' % (module, line, function),
file=sys.stderr)
@@ -1525,9 +1525,9 @@
- the line number of the offending code;
- the function name of the offending code.
"""
- type, value, traceback = sys.exc_info()
+ typ, value, traceback = sys.exc_info()
while traceback.tb_next:
traceback = traceback.tb_next
code = traceback.tb_frame.f_code
- return (type.__name__, value, code.co_filename, traceback.tb_lineno,
+ return (typ.__name__, value, code.co_filename, traceback.tb_lineno,
code.co_name)
Modified: trunk/docutils/docutils/transforms/peps.py
===================================================================
--- trunk/docutils/docutils/transforms/peps.py 2024-08-01 21:25:56 UTC (rev 9839)
+++ trunk/docutils/docutils/transforms/peps.py 2024-08-01 21:56:03 UTC (rev 9840)
@@ -174,7 +174,7 @@
def apply(self) -> None:
doc = self.document
i = len(doc) - 1
- refsect = copyright = None
+ refsect = copyright_ = None
while i >= 0 and isinstance(doc[i], nodes.section):
title_words = doc[i][0].astext().lower().split()
if 'references' in title_words:
@@ -181,15 +181,15 @@
refsect = doc[i]
break
elif 'copyright' in title_words:
- copyright = i
+ copyright_ = i
i -= 1
if not refsect:
refsect = nodes.section()
refsect += nodes.title('', 'References')
doc.set_id(refsect)
- if copyright:
+ if copyright_:
# Put the new "References" section before "Copyright":
- doc.insert(copyright, refsect)
+ doc.insert(copyright_, refsect)
else:
# Put the new "References" section at end of doc:
doc.append(refsect)
Modified: trunk/docutils/docutils/utils/math/math2html.py
===================================================================
--- trunk/docutils/docutils/utils/math/math2html.py 2024-08-01 21:25:56 UTC (rev 9839)
+++ trunk/docutils/docutils/utils/math/math2html.py 2024-08-01 21:56:03 UTC (rev 9840)
@@ -699,18 +699,18 @@
def extract(self, container):
"Extract a group of selected containers from a container."
- list = []
+ lst = []
locate = lambda c: c.__class__.__name__ in self.allowed
recursive = lambda c: c.__class__.__name__ in self.extracted
- process = lambda c: self.process(c, list)
+ process = lambda c: self.process(c, lst)
container.recursivesearch(locate, recursive, process)
- return list
+ return lst
- def process(self, container, list) -> None:
+ def process(self, container, lst) -> None:
"Add allowed containers."
name = container.__class__.__name__
if name in self.allowed:
- list.append(container)
+ lst.append(container)
else:
Trace.error('Unknown container class ' + name)
@@ -944,10 +944,10 @@
"Get opening line."
if not self.checktag(container):
return ''
- open = '<' + self.tag + '>'
+ open_tag = '<' + self.tag + '>'
if self.breaklines:
- return open + '\n'
- return open
+ return open_tag + '\n'
+ return open_tag
def close(self, container):
"Get closing line."
@@ -1355,16 +1355,16 @@
def searchall(self, type):
"Search for all embedded containers of a given type"
- list = []
- self.searchprocess(type, lambda container: list.append(container))
- return list
+ lst = []
+ self.searchprocess(type, lambda container: lst.append(container))
+ return lst
def searchremove(self, type):
"Search for all containers of a type and remove them"
- list = self.searchall(type)
- for container in list:
+ lst = self.searchall(type)
+ for container in lst:
container.parent.contents.remove(container)
- return list
+ return lst
def searchprocess(self, type, process) -> None:
"Search for elements of a given type and process them"
Modified: trunk/docutils/docutils/writers/odf_odt/__init__.py
===================================================================
--- trunk/docutils/docutils/writers/odf_odt/__init__.py 2024-08-01 21:25:56 UTC (rev 9839)
+++ trunk/docutils/docutils/writers/odf_odt/__init__.py 2024-08-01 21:56:03 UTC (rev 9840)
@@ -291,13 +291,13 @@
text = text.replace("&", "&")
text = text.replace("<", "<")
text = text.replace(">", ">")
- ascii = ''
+ ascii_ = ''
for char in text:
if ord(char) >= ord("\x7f"):
- ascii += "&#x%X;" % (ord(char), )
+ ascii_ += "&#x%X;" % (ord(char), )
else:
- ascii += char
- return ascii
+ ascii_ += char
+ return ascii_
#
@@ -633,7 +633,7 @@
return updated, stylesheet_root, modified_nodes
def write_zip_str(
- self, zfile, name, bytes, compress_type=zipfile.ZIP_DEFLATED,
+ self, zfile, name, bytes_, compress_type=zipfile.ZIP_DEFLATED,
) -> None:
localtime = time.localtime(time.time())
zinfo = zipfile.ZipInfo(name, localtime)
@@ -640,7 +640,7 @@
# Add some standard UNIX file access permissions (-rw-r--r--).
zinfo.external_attr = (0x81a4 & 0xFFFF) << 16
zinfo.compress_type = compress_type
- zfile.writestr(zinfo, bytes)
+ zfile.writestr(zinfo, bytes_)
def store_embedded_files(self, zfile) -> None:
embedded_files = self.visitor.get_embedded_file_list()
@@ -964,10 +964,10 @@
if family == 'table':
properties = stylenode.find(
'{%s}table-properties' % (CNSD['style'], ))
- property = properties.get(
+ property_ = properties.get(
'{%s}%s' % (CNSD['fo'], 'background-color', ))
- if property is not None and property != 'none':
- tablestyle.backgroundcolor = property
+ if property_ is not None and property_ != 'none':
+ tablestyle.backgroundcolor = property_
elif family == 'table-cell':
properties = stylenode.find(
'{%s}table-cell-properties' % (CNSD['style'], ))
Modified: trunk/docutils/test/alltests.py
===================================================================
--- trunk/docutils/test/alltests.py 2024-08-01 21:25:56 UTC (rev 9839)
+++ trunk/docutils/test/alltests.py 2024-08-01 21:56:03 UTC (rev 9840)
@@ -12,7 +12,7 @@
All modules named 'test_*.py' in the current directory, and recursively in
subdirectories (packages) called 'test_*', are loaded and test suites within
are run.
-"""
+""" # NoQA: A001
import atexit
import platform
Modified: trunk/docutils/test/test_io.py
===================================================================
--- trunk/docutils/test/test_io.py 2024-08-01 21:25:56 UTC (rev 9839)
+++ trunk/docutils/test/test_io.py 2024-08-01 21:56:03 UTC (rev 9840)
@@ -115,41 +115,41 @@
# default input encoding will change to UTF-8 in Docutils 0.22
source = '\ufeffdata\n\ufeff blah\n'
expected = 'data\n\ufeff blah\n' # only leading ZWNBSP removed
- input = du_io.StringInput(source=source.encode('utf-16-be'),
- encoding=None)
- self.assertEqual(expected, input.read())
- input = du_io.StringInput(source=source.encode('utf-16-le'),
- encoding=None)
- self.assertEqual(expected, input.read())
- input = du_io.StringInput(source=source.encode('utf-8'),
- encoding=None)
- self.assertEqual(expected, input.read())
+ input_ = du_io.StringInput(source=source.encode('utf-16-be'),
+ encoding=None)
+ self.assertEqual(expected, input_.read())
+ input_ = du_io.StringInput(source=source.encode('utf-16-le'),
+ encoding=None)
+ self.assertEqual(expected, input_.read())
+ input_ = du_io.StringInput(source=source.encode('utf-8'),
+ encoding=None)
+ self.assertEqual(expected, input_.read())
# With `str` input all ZWNBSPs are still there.
- input = du_io.StringInput(source=source)
- self.assertEqual(source, input.read())
+ input_ = du_io.StringInput(source=source)
+ self.assertEqual(source, input_.read())
def test_encoding_declaration(self):
- input = du_io.StringInput(source=b"""\
+ input_ = du_io.StringInput(source=b"""\
.. -*- coding: ascii -*-
data
blah
""", encoding=None)
- data = input.read() # noqa: F841
- self.assertEqual('ascii', input.successful_encoding)
- input = du_io.StringInput(source=b"""\
+ data = input_.read() # noqa: F841
+ self.assertEqual('ascii', input_.successful_encoding)
+ input_ = du_io.StringInput(source=b"""\
#! python
# -*- coding: ascii -*-
print("hello world")
""", encoding=None)
- data = input.read() # noqa: F841
- self.assertEqual('ascii', input.successful_encoding)
- input = du_io.StringInput(source=b"""\
+ data = input_.read() # noqa: F841
+ self.assertEqual('ascii', input_.successful_encoding)
+ input_ = du_io.StringInput(source=b"""\
#! python
# extraneous comment; prevents coding slug from being read
# -*- coding: ascii -*-
print("hello world")
""")
- self.assertNotEqual(input.successful_encoding, 'ascii')
+ self.assertNotEqual(input_.successful_encoding, 'ascii')
def test_decode_unicode(self):
# With the special value "unicode" or "Unicode":
Modified: trunk/docutils/test/test_nodes.py
===================================================================
--- trunk/docutils/test/test_nodes.py 2024-08-01 21:25:56 UTC (rev 9839)
+++ trunk/docutils/test/test_nodes.py 2024-08-01 21:56:03 UTC (rev 9840)
@@ -1084,8 +1084,8 @@
def test_make_id(self):
failures = []
tests = self.ids + self.ids_unicode_all
- for input, expect in tests:
- output = nodes.make_id(input)
+ for input_, expect in tests:
+ output = nodes.make_id(input_)
if expect != output:
failures.append("'%s' != '%s'" % (expect, output))
if failures:
Modified: trunk/docutils/test/test_utils/test__init__.py
===================================================================
--- trunk/docutils/test/test_utils/test__init__.py 2024-08-01 21:25:56 UTC (rev 9839)
+++ trunk/docutils/test/test_utils/test__init__.py 2024-08-01 21:56:03 UTC (rev 9840)
@@ -184,16 +184,16 @@
'empty': (lambda x: x)}
def test_assemble_option_dict(self):
- input = utils.extract_name_value('a=1 bbb=2.0 cdef=hol%s' % chr(224))
+ input_ = utils.extract_name_value('a=1 bbb=2.0 cdef=hol%s' % chr(224))
self.assertEqual(
- utils.assemble_option_dict(input, self.optionspec),
+ utils.assemble_option_dict(input_, self.optionspec),
{'a': 1, 'bbb': 2.0, 'cdef': ('hol%s' % chr(224))})
- input = utils.extract_name_value('a=1 b=2.0 c=hol%s' % chr(224))
+ input_ = utils.extract_name_value('a=1 b=2.0 c=hol%s' % chr(224))
with self.assertRaises(KeyError):
- utils.assemble_option_dict(input, self.optionspec)
- input = utils.extract_name_value('a=1 bbb=two cdef=hol%s' % chr(224))
+ utils.assemble_option_dict(input_, self.optionspec)
+ input_ = utils.extract_name_value('a=1 bbb=two cdef=hol%s' % chr(224))
with self.assertRaises(ValueError):
- utils.assemble_option_dict(input, self.optionspec)
+ utils.assemble_option_dict(input_, self.optionspec)
def test_extract_extension_options(self):
field_list = nodes.field_list()
Modified: trunk/docutils/tools/dev/quicktest.py
===================================================================
--- trunk/docutils/tools/dev/quicktest.py 2024-08-01 21:25:56 UTC (rev 9839)
+++ trunk/docutils/tools/dev/quicktest.py 2024-08-01 21:56:03 UTC (rev 9840)
@@ -108,19 +108,19 @@
def _pretty(
- input: str, document: nodes.document, optargs: _OptArgs,
+ input_: str, document: nodes.document, optargs: _OptArgs,
) -> str:
return document.pformat()
def _rawxml(
- input: str, document: nodes.document, optargs: _OptArgs,
+ input_: str, document: nodes.document, optargs: _OptArgs,
) -> str:
return document.asdom().toxml()
def _styledxml(
- input: str, document: nodes.document, optargs: _OptArgs,
+ input_: str, document: nodes.document, optargs: _OptArgs,
) -> str:
docnode = document.asdom().childNodes[0]
return '\n'.join(('<?xml version="1.0" encoding="ISO-8859-1"?>',
@@ -130,13 +130,13 @@
def _prettyxml(
- input: str, document: nodes.document, optargs: _OptArgs,
+ input_: str, document: nodes.document, optargs: _OptArgs,
) -> str:
return document.asdom().toprettyxml(' ', '\n')
def _test(
- input: str, document: nodes.document, optargs: _OptArgs,
+ input_: str, document: nodes.document, optargs: _OptArgs,
) -> str:
tq = '"""'
output = document.pformat() # same as _pretty()
@@ -149,7 +149,7 @@
%s
%s],
]
-""" % (tq, escape(input.rstrip()), tq, tq, escape(output.rstrip()), tq)
+""" % (tq, escape(input_.rstrip()), tq, tq, escape(output.rstrip()), tq)
def escape(text: str) -> str:
@@ -173,12 +173,12 @@
def format(
output_format: str,
- input: str,
+ input_: str,
document: nodes.document,
optargs: _OptArgs,
) -> str:
formatter = _output_formatters[output_format]
- return formatter(input, document, optargs)
+ return formatter(input_, document, optargs)
def posix_get_args(argv: list[str]) -> tuple[TextIO, TextIO, str, _OptArgs]:
@@ -241,10 +241,10 @@
settings = frontend.get_default_settings(Parser)
settings.debug = optargs['debug']
parser = Parser()
- input = input_file.read()
+ input_ = input_file.read()
document = new_document(input_file.name, settings)
- parser.parse(input, document)
- output = format(output_format, input, document, optargs)
+ parser.parse(input_, document)
+ output = format(output_format, input_, document, optargs)
output_file.write(output)
if optargs['attributes']:
import pprint
Modified: trunk/docutils/tools/dev/unicode2rstsubs.py
===================================================================
--- trunk/docutils/tools/dev/unicode2rstsubs.py 2024-08-01 21:25:56 UTC (rev 9839)
+++ trunk/docutils/tools/dev/unicode2rstsubs.py 2024-08-01 21:56:03 UTC (rev 9840)
@@ -134,18 +134,18 @@
self.charid = attributes['id']
def entity_start(self, name, attributes) -> None:
- set = self.entity_set_name(attributes['set'])
- if not set:
+ set_ = self.entity_set_name(attributes['set'])
+ if not set_:
return
- if set not in self.sets:
- print('bad set: %r' % set)
+ if set_ not in self.sets:
+ print('bad set: %r' % set_)
return
entity = attributes['id']
- assert (entity not in self.sets[set]
- or self.sets[set][entity] == self.charid
+ assert (entity not in self.sets[set_]
+ or self.sets[set_][entity] == self.charid
), ('sets[%r][%r] == %r (!= %r)'
- % (set, entity, self.sets[set][entity], self.charid))
- self.sets[set][entity] = self.charid
+ % (set_, entity, self.sets[set_][entity], self.charid))
+ self.sets[set_][entity] = self.charid
def description_data(self, data) -> None:
self.descriptions.setdefault(self.charid, '')
@@ -179,8 +179,8 @@
outfile = open(outname, 'w', encoding='ascii')
print('writing file "%s"' % outname)
outfile.write(self.header + '\n')
- set = self.sets[set_name]
- entities = sorted((e.lower(), e) for e in set.keys())
+ set_ = self.sets[set_name]
+ entities = sorted((e.lower(), e) for e in set_.keys())
longest = 0
for _, entity_name in entities:
longest = max(longest, len(entity_name))
@@ -187,13 +187,14 @@
has_wide = False
for _, entity_name in entities:
has_wide = self.write_entity(
- set, set_name, entity_name, outfile, longest, wide) or has_wide
+ set_, set_name, entity_name, outfile, longest, wide,
+ ) or has_wide
if has_wide and not wide:
self.write_set(set_name, wide=True)
def write_entity(
self,
- set: dict[str, str],
+ set_: dict[str, str],
set_name: str,
entity_name: str,
outfile: TextIO,
@@ -200,7 +201,7 @@
longest: int,
wide: bool = False,
) -> bool:
- charid = set[entity_name]
+ charid = set_[entity_name]
if not wide:
for code in charid[1:].split('-'):
if int(code, 16) > 0xFFFF:
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <aa-...@us...> - 2024-08-01 22:27:22
|
Revision: 9841
http://sourceforge.net/p/docutils/code/9841
Author: aa-turner
Date: 2024-08-01 22:27:19 +0000 (Thu, 01 Aug 2024)
Log Message:
-----------
Enable the refurb linter in Ruff
Modified Paths:
--------------
trunk/docutils/.ruff.toml
trunk/docutils/docutils/transforms/peps.py
trunk/docutils/docutils/utils/__init__.py
trunk/docutils/docutils/utils/math/math2html.py
trunk/docutils/docutils/utils/math/tex2mathml_extern.py
trunk/docutils/docutils/writers/_html_base.py
trunk/docutils/docutils/writers/manpage.py
trunk/docutils/docutils/writers/odf_odt/__init__.py
trunk/docutils/docutils/writers/s5_html/__init__.py
trunk/docutils/test/test_CLI.py
trunk/docutils/test/test_dependencies.py
trunk/docutils/test/test_parsers/test_rst/test_TableParser.py
trunk/docutils/test/test_parsers/test_rst/test_directives/test_tables.py
trunk/docutils/test/test_utils/test_math/test_tex2mathml_extern.py
trunk/docutils/tools/buildhtml.py
trunk/docutils/tools/dev/create_unimap.py
Modified: trunk/docutils/.ruff.toml
===================================================================
--- trunk/docutils/.ruff.toml 2024-08-01 21:56:03 UTC (rev 9840)
+++ trunk/docutils/.ruff.toml 2024-08-01 22:27:19 UTC (rev 9841)
@@ -12,6 +12,7 @@
"DTZ", # flake8-datetimez
"F", # pyflakes
"FA", # flake8-future-annotations
+ "FURB", # refurb
"G", # flake8-logging-format
"ICN", # flake8-import-conventions
"INP", # flake8-no-pep420
Modified: trunk/docutils/docutils/transforms/peps.py
===================================================================
--- trunk/docutils/docutils/transforms/peps.py 2024-08-01 21:56:03 UTC (rev 9840)
+++ trunk/docutils/docutils/transforms/peps.py 2024-08-01 22:27:19 UTC (rev 9841)
@@ -117,11 +117,14 @@
space = nodes.Text(' ')
for refpep in re.split(r',?\s+', body.astext()):
pepno = int(refpep)
- newbody.append(nodes.reference(
- refpep, refpep,
- refuri=(self.document.settings.pep_base_url
- + self.pep_url % pepno)))
- newbody.append(space)
+ newbody.extend((
+ nodes.reference(
+ refpep, refpep,
+ refuri=(self.document.settings.pep_base_url
+ + self.pep_url % pepno)
+ ),
+ space,
+ ))
para[:] = newbody[:-1] # drop trailing space
elif name == 'last-modified':
utils.clean_rcs_keywords(para, self.rcs_keyword_substitutions)
Modified: trunk/docutils/docutils/utils/__init__.py
===================================================================
--- trunk/docutils/docutils/utils/__init__.py 2024-08-01 21:56:03 UTC (rev 9840)
+++ trunk/docutils/docutils/utils/__init__.py 2024-08-01 22:27:19 UTC (rev 9841)
@@ -626,8 +626,10 @@
if found == -1:
parts.append(text[start:])
return ''.join(parts)
- parts.append(text[start:found])
- parts.append('\x00' + text[found+1:found+2])
+ parts.extend((
+ text[start:found],
+ '\x00' + text[found + 1:found + 2],
+ ))
start = found + 2 # skip character after escape
Modified: trunk/docutils/docutils/utils/math/math2html.py
===================================================================
--- trunk/docutils/docutils/utils/math/math2html.py 2024-08-01 21:56:03 UTC (rev 9840)
+++ trunk/docutils/docutils/utils/math/math2html.py 2024-08-01 22:27:19 UTC (rev 9841)
@@ -1848,10 +1848,11 @@
def innertext(self, pos) -> None:
"Parse some text inside the bracket, following textual rules."
- specialchars = list(FormulaConfig.symbolfunctions.keys())
- specialchars.append(FormulaConfig.starts['command'])
- specialchars.append(FormulaConfig.starts['bracket'])
- specialchars.append(Comment.start)
+ specialchars = list(FormulaConfig.symbolfunctions.keys()) + [
+ FormulaConfig.starts['command'],
+ FormulaConfig.starts['bracket'],
+ Comment.start,
+ ]
while not pos.finished():
if pos.current() in specialchars:
self.add(self.factory.parseany(pos))
Modified: trunk/docutils/docutils/utils/math/tex2mathml_extern.py
===================================================================
--- trunk/docutils/docutils/utils/math/tex2mathml_extern.py 2024-08-01 21:56:03 UTC (rev 9840)
+++ trunk/docutils/docutils/utils/math/tex2mathml_extern.py 2024-08-01 22:27:19 UTC (rev 9841)
@@ -174,10 +174,12 @@
details = []
if result.stderr:
lines = result.stderr.splitlines()
- details.append(nodes.paragraph('', lines[0]))
- details.append(nodes.literal_block('', '\n'.join(lines[1:3])))
- details.append(nodes.paragraph('', '\n'.join(lines[3:]),
- classes=['pre-wrap']))
+ details.extend((
+ nodes.paragraph('', lines[0]),
+ nodes.literal_block('', '\n'.join(lines[1:3])),
+ nodes.paragraph('', '\n'.join(lines[3:]),
+ classes=['pre-wrap']),
+ ))
_check_result(result, details=details)
return result.stdout
Modified: trunk/docutils/docutils/writers/_html_base.py
===================================================================
--- trunk/docutils/docutils/writers/_html_base.py 2024-08-01 21:56:03 UTC (rev 9840)
+++ trunk/docutils/docutils/writers/_html_base.py 2024-08-01 22:27:19 UTC (rev 9841)
@@ -159,8 +159,8 @@
self.output = self.apply_template()
def apply_template(self):
- with open(self.document.settings.template, encoding='utf-8') as fp:
- template = fp.read()
+ template_path = Path(self.document.settings.template)
+ template = template_path.read_text(encoding='utf-8')
subs = self.interpolation_dict()
return template % subs
@@ -506,8 +506,7 @@
adjust_path = bool(self.settings.stylesheet_path)
if self.settings.embed_stylesheet:
try:
- with open(path, encoding='utf-8') as f:
- content = f.read()
+ content = Path(path).read_text(encoding='utf-8')
except OSError as err:
msg = f'Cannot embed stylesheet: {err}'
self.document.reporter.error(msg)
@@ -1170,8 +1169,7 @@
elif loading == 'embed':
try:
imagepath = self.uri2imagepath(uri)
- with open(imagepath, 'rb') as imagefile:
- imagedata = imagefile.read()
+ imagedata = Path(imagepath).read_bytes()
except (ValueError, OSError) as err:
self.messages.append(self.document.reporter.error(
f'Cannot embed image "{uri}":\n {err}', base_node=node))
Modified: trunk/docutils/docutils/writers/manpage.py
===================================================================
--- trunk/docutils/docutils/writers/manpage.py 2024-08-01 21:56:03 UTC (rev 9840)
+++ trunk/docutils/docutils/writers/manpage.py 2024-08-01 22:27:19 UTC (rev 9841)
@@ -174,9 +174,11 @@
del cell_lines[-1]
def as_list(self):
- text = ['.TS\n']
- text.append(' '.join(self._options) + ';\n')
- text.append('%s.\n' % ('|'.join(self._coldefs)))
+ text = [
+ '.TS\n',
+ ' '.join(self._options) + ';\n',
+ '%s.\n' % '|'.join(self._coldefs),
+ ]
for row in self._rows:
# row = array of cells. cell = array of lines.
text.append('T{\n')
Modified: trunk/docutils/docutils/writers/odf_odt/__init__.py
===================================================================
--- trunk/docutils/docutils/writers/odf_odt/__init__.py 2024-08-01 21:56:03 UTC (rev 9840)
+++ trunk/docutils/docutils/writers/odf_odt/__init__.py 2024-08-01 22:27:19 UTC (rev 9841)
@@ -930,8 +930,7 @@
stylespath = self.settings.stylesheet
ext = os.path.splitext(stylespath)[1]
if ext == '.xml':
- with open(stylespath, 'r', encoding='utf-8') as stylesfile:
- s1 = stylesfile.read()
+ s1 = Path(stylespath).read_text(encoding='utf-8')
elif ext == extension:
zfile = zipfile.ZipFile(stylespath, 'r')
s1 = zfile.read('styles.xml')
@@ -2629,8 +2628,7 @@
my_lines.append(my_line)
my_lines_str = '<text:line-break/>'.join(my_lines)
my_lines_str2 = wrapper1 % (my_lines_str, )
- lines1.append(my_lines_str2)
- lines1.append('</wrappertag1>')
+ lines1.extend((my_lines_str2, '</wrappertag1>'))
s1 = ''.join(lines1)
s1 = s1.encode("utf-8")
el1 = etree.fromstring(s1)
Modified: trunk/docutils/docutils/writers/s5_html/__init__.py
===================================================================
--- trunk/docutils/docutils/writers/s5_html/__init__.py 2024-08-01 21:56:03 UTC (rev 9840)
+++ trunk/docutils/docutils/writers/s5_html/__init__.py 2024-08-01 22:27:19 UTC (rev 9841)
@@ -9,9 +9,11 @@
__docformat__ = 'reStructuredText'
-import sys
import os
import re
+import sys
+from pathlib import Path
+
import docutils
from docutils import frontend, nodes, utils
from docutils.writers import html4css1
@@ -266,14 +268,12 @@
if os.path.exists(dest) and not settings.overwrite_theme_files:
settings.record_dependencies.add(dest)
else:
- with open(source, 'rb') as src_file:
- src_data = src_file.read()
- with open(dest, 'wb') as dest_file:
- dest_dir = dest_dir.replace(os.sep, '/')
- dest_file.write(src_data.replace(
- b'ui/default',
- dest_dir[dest_dir.rfind('ui/'):].encode(
- sys.getfilesystemencoding())))
+ src_data = Path(source).read_bytes()
+ dest_dir = dest_dir.replace(os.sep, '/')
+ Path(dest).write_bytes(src_data.replace(
+ b'ui/default',
+ dest_dir[dest_dir.rfind('ui/'):].encode(
+ sys.getfilesystemencoding())))
settings.record_dependencies.add(source)
return True
if os.path.isfile(dest):
Modified: trunk/docutils/test/test_CLI.py
===================================================================
--- trunk/docutils/test/test_CLI.py 2024-08-01 21:56:03 UTC (rev 9840)
+++ trunk/docutils/test/test_CLI.py 2024-08-01 22:27:19 UTC (rev 9841)
@@ -85,8 +85,7 @@
# compare to stored version
docutils_txt = os.path.join(DATA_ROOT, 'help/docutils.txt')
- with open(docutils_txt, encoding='utf-8') as samplefile:
- expected = samplefile.read()
+ expected = Path(docutils_txt).read_text(encoding='utf-8')
if expected != output:
print_mismatch(expected, output)
@@ -95,8 +94,7 @@
output = self.get_help_text('rst2html', core.rst2html)
# compare to stored version
rst2html_txt = os.path.join(DATA_ROOT, 'help/rst2html.txt')
- with open(rst2html_txt, encoding='utf-8') as samplefile:
- expected = samplefile.read()
+ expected = Path(rst2html_txt).read_text(encoding='utf-8')
if expected != output:
print_mismatch(expected, output)
@@ -105,8 +103,7 @@
output = self.get_help_text('rst2latex', core.rst2latex)
# compare to stored version
rst2latex_txt = os.path.join(DATA_ROOT, 'help/rst2latex.txt')
- with open(rst2latex_txt, encoding='utf-8') as samplefile:
- expected = samplefile.read()
+ expected = Path(rst2latex_txt).read_text(encoding='utf-8')
if expected != output:
print_mismatch(expected, output)
Modified: trunk/docutils/test/test_dependencies.py
===================================================================
--- trunk/docutils/test/test_dependencies.py 2024-08-01 21:56:03 UTC (rev 9840)
+++ trunk/docutils/test/test_dependencies.py 2024-08-01 22:27:19 UTC (rev 9841)
@@ -65,8 +65,8 @@
**kwargs)
recorder.close()
# Read the record file:
- with open(recordfile, encoding='utf-8') as record:
- return record.read().splitlines(), output
+ records = Path(recordfile).read_text(encoding='utf-8').splitlines()
+ return records, output
def test_dependencies_xml(self):
# Note: currently, raw input files are read (and hence recorded) while
Modified: trunk/docutils/test/test_parsers/test_rst/test_TableParser.py
===================================================================
--- trunk/docutils/test/test_parsers/test_rst/test_TableParser.py 2024-08-01 21:56:03 UTC (rev 9840)
+++ trunk/docutils/test/test_parsers/test_rst/test_TableParser.py 2024-08-01 22:27:19 UTC (rev 9841)
@@ -24,7 +24,7 @@
def test_parse_table(self):
parser = tableparser.GridTableParser()
for name, cases in totest.items():
- for casenum, case in enumerate(cases):
+ for case in cases:
case_input, case_table, _case_expected = case
lines_input = StringList(string2lines(case_input), 'test data')
parser.setup(lines_input)
Modified: trunk/docutils/test/test_parsers/test_rst/test_directives/test_tables.py
===================================================================
--- trunk/docutils/test/test_parsers/test_rst/test_directives/test_tables.py 2024-08-01 21:56:03 UTC (rev 9840)
+++ trunk/docutils/test/test_parsers/test_rst/test_directives/test_tables.py 2024-08-01 22:27:19 UTC (rev 9841)
@@ -67,8 +67,7 @@
try:
- with open(utf_16_csv, 'rb') as f:
- csv_data = f.read()
+ csv_data = Path(utf_16_csv).read_bytes()
csv_data = str(csv_data, 'latin1').splitlines()
reader = csv.reader([line + '\n' for line in csv_data])
next(reader)
Modified: trunk/docutils/test/test_utils/test_math/test_tex2mathml_extern.py
===================================================================
--- trunk/docutils/test/test_utils/test_math/test_tex2mathml_extern.py 2024-08-01 21:56:03 UTC (rev 9840)
+++ trunk/docutils/test/test_utils/test_math/test_tex2mathml_extern.py 2024-08-01 22:27:19 UTC (rev 9841)
@@ -146,8 +146,7 @@
'buggy-maths',
writer='html5',
settings_overrides=settings)
- with open(out_path, "w") as fd:
- fd.write(parts['whole'])
+ Path(out_path).write_text(parts['whole'])
with self.subTest(converter=math_output[1] or 'latex2mathml()'):
compare_output(parts['whole'], out_path, expected_path)
Modified: trunk/docutils/tools/buildhtml.py
===================================================================
--- trunk/docutils/tools/buildhtml.py 2024-08-01 21:56:03 UTC (rev 9840)
+++ trunk/docutils/tools/buildhtml.py 2024-08-01 22:27:19 UTC (rev 9841)
@@ -295,7 +295,7 @@
errout.write('/// ...Skipping directory (pruned): %s\n'
% relative_path(None, dirpath))
sys.stderr.flush()
- del dirnames[:] # modify in-place to control `os.walk()` run
+ dirnames.clear() # modify in-place to control `os.walk()` run
return
if not self.initial_settings.silent:
errout.write('/// Processing directory: %s\n'
Modified: trunk/docutils/tools/dev/create_unimap.py
===================================================================
--- trunk/docutils/tools/dev/create_unimap.py 2024-08-01 21:56:03 UTC (rev 9840)
+++ trunk/docutils/tools/dev/create_unimap.py 2024-08-01 22:27:19 UTC (rev 9841)
@@ -68,7 +68,7 @@
print('# $%s$' % 'Id')
print('# Author: Lea Wiemann <LeW...@gm...>')
print('# Copyright: This file has been placed in the public domain.')
-print('')
+print()
print('# This is a mapping of Unicode characters to LaTeX equivalents.')
print('# The information has been extracted from')
print('# <https://www.w3.org/2003/entities/xml/unicode.xml>, written by')
@@ -76,5 +76,5 @@
print('#')
print('# The extraction has been done by the "create_unimap.py" script')
print('# located at <https://docutils.sourceforge.io/tools/dev/create_unimap.py>.') # noqa:501
-print('')
+print()
print('unicode_map = %s' % pprint.pformat(unicode_map, indent=0))
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <aa-...@us...> - 2024-08-01 22:41:30
|
Revision: 9842
http://sourceforge.net/p/docutils/code/9842
Author: aa-turner
Date: 2024-08-01 22:41:27 +0000 (Thu, 01 Aug 2024)
Log Message:
-----------
Enable the perflint linter in Ruff
Modified Paths:
--------------
trunk/docutils/.ruff.toml
trunk/docutils/docutils/nodes.py
trunk/docutils/docutils/parsers/rst/states.py
trunk/docutils/docutils/transforms/frontmatter.py
trunk/docutils/docutils/transforms/references.py
trunk/docutils/docutils/utils/__init__.py
trunk/docutils/docutils/utils/math/math2html.py
trunk/docutils/docutils/writers/html4css1/__init__.py
trunk/docutils/test/test_parsers/test_rst/test_TableParser.py
trunk/docutils/tools/buildhtml.py
Modified: trunk/docutils/.ruff.toml
===================================================================
--- trunk/docutils/.ruff.toml 2024-08-01 22:27:19 UTC (rev 9841)
+++ trunk/docutils/.ruff.toml 2024-08-01 22:41:27 UTC (rev 9842)
@@ -18,6 +18,7 @@
"INP", # flake8-no-pep420
"INT", # flake8-gettext
"LOG", # flake8-logging
+ "PERF", # perflint
"PGH", # pygrep-hooks
"PIE", # flake8-pie
"PT", # flake8-pytest
@@ -37,6 +38,9 @@
# whitespace around the operators with the lowest priority(ies).
# Use your own judgment; …"
+ "PERF203", # ``try``-``except`` within a loop incurs performance overhead
+ # Needs more thought.
+
"PT009", # Use a regular assert instead of unittest-style
"PT027", # Use pytest.raises instead of unittest-style
# We still use unittest.
Modified: trunk/docutils/docutils/nodes.py
===================================================================
--- trunk/docutils/docutils/nodes.py 2024-08-01 22:27:19 UTC (rev 9841)
+++ trunk/docutils/docutils/nodes.py 2024-08-01 22:41:27 UTC (rev 9842)
@@ -776,10 +776,10 @@
[child.astext() for child in self.children])
def non_default_attributes(self) -> dict[str, Any]:
- atts = {}
- for key, value in self.attributes.items():
- if self.is_not_default(key):
- atts[key] = value
+ atts = {
+ key: value for key, value in self.attributes.items()
+ if self.is_not_default(key)
+ }
return atts
def attlist(self) -> list[tuple[str, Any]]:
Modified: trunk/docutils/docutils/parsers/rst/states.py
===================================================================
--- trunk/docutils/docutils/parsers/rst/states.py 2024-08-01 22:27:19 UTC (rev 9841)
+++ trunk/docutils/docutils/parsers/rst/states.py 2024-08-01 22:41:27 UTC (rev 9842)
@@ -2889,9 +2889,10 @@
text = parts[0].rstrip()
textnode = nodes.Text(text)
node_list[-1] += textnode
- for part in parts[1:]:
- node_list.append(
- nodes.classifier(unescape(part, True), part))
+ node_list += [
+ nodes.classifier(unescape(part, True), part)
+ for part in parts[1:]
+ ]
else:
node_list[-1] += node
return node_list, messages
Modified: trunk/docutils/docutils/transforms/frontmatter.py
===================================================================
--- trunk/docutils/docutils/transforms/frontmatter.py 2024-08-01 22:27:19 UTC (rev 9841)
+++ trunk/docutils/docutils/transforms/frontmatter.py 2024-08-01 22:41:27 UTC (rev 9842)
@@ -418,9 +418,10 @@
nodelist = []
if len(docinfo) != 0:
nodelist.append(docinfo)
- for name in ('dedication', 'abstract'):
- if topics[name]:
- nodelist.append(topics[name])
+ if topics['dedication']:
+ nodelist.append(topics['dedication'])
+ if topics['abstract']:
+ nodelist.append(topics['abstract'])
return nodelist
def check_empty_biblio_field(self, field, name) -> bool:
Modified: trunk/docutils/docutils/transforms/references.py
===================================================================
--- trunk/docutils/docutils/transforms/references.py 2024-08-01 22:27:19 UTC (rev 9841)
+++ trunk/docutils/docutils/transforms/references.py 2024-08-01 22:41:27 UTC (rev 9842)
@@ -113,14 +113,15 @@
default_priority = 440
def apply(self) -> None:
- anonymous_refs = []
- anonymous_targets = []
- for node in self.document.findall(nodes.reference):
- if node.get('anonymous'):
- anonymous_refs.append(node)
- for node in self.document.findall(nodes.target):
- if node.get('anonymous'):
- anonymous_targets.append(node)
+ anonymous_refs = [
+ node for node
+ in self.document.findall(nodes.reference)
+ if node.get('anonymous')]
+ anonymous_targets = [
+ node for node
+ in self.document.findall(nodes.target)
+ if node.get('anonymous')
+ ]
if len(anonymous_refs) != len(anonymous_targets):
msg = self.document.reporter.error(
'Anonymous hyperlink mismatch: %s references but %s '
Modified: trunk/docutils/docutils/utils/__init__.py
===================================================================
--- trunk/docutils/docutils/utils/__init__.py 2024-08-01 22:27:19 UTC (rev 9841)
+++ trunk/docutils/docutils/utils/__init__.py 2024-08-01 22:41:27 UTC (rev 9842)
@@ -725,10 +725,11 @@
subtags = list(tag.split('_'))
base_tag = (subtags.pop(0),)
# find all combinations of subtags
- taglist = []
- for n in range(len(subtags), 0, -1):
- for tags in itertools.combinations(subtags, n):
- taglist.append('-'.join(base_tag+tags))
+ taglist = [
+ '-'.join(base_tag + tags)
+ for n in range(len(subtags), 0, -1)
+ for tags in itertools.combinations(subtags, n)
+ ]
taglist += base_tag
return taglist
Modified: trunk/docutils/docutils/utils/math/math2html.py
===================================================================
--- trunk/docutils/docutils/utils/math/math2html.py 2024-08-01 22:27:19 UTC (rev 9841)
+++ trunk/docutils/docutils/utils/math/math2html.py 2024-08-01 22:41:27 UTC (rev 9842)
@@ -991,10 +991,8 @@
def gethtml(self, container):
"Return the HTML code"
- result = []
html = ContentsOutput.gethtml(self, container)
- for line in html:
- result.append(self.filter(line))
+ result = [self.filter(line) for line in html]
return result
def filter(self, line):
Modified: trunk/docutils/docutils/writers/html4css1/__init__.py
===================================================================
--- trunk/docutils/docutils/writers/html4css1/__init__.py 2024-08-01 22:27:19 UTC (rev 9841)
+++ trunk/docutils/docutils/writers/html4css1/__init__.py 2024-08-01 22:41:27 UTC (rev 9842)
@@ -932,10 +932,10 @@
"""
def visit_list_item(self, node):
- children = []
- for child in node.children:
- if not isinstance(child, nodes.Invisible):
- children.append(child)
+ children = [
+ child for child in node.children
+ if not isinstance(child, nodes.Invisible)
+ ]
if (children and isinstance(children[0], nodes.paragraph)
and (isinstance(children[-1], nodes.bullet_list)
or isinstance(children[-1], nodes.enumerated_list))):
Modified: trunk/docutils/test/test_parsers/test_rst/test_TableParser.py
===================================================================
--- trunk/docutils/test/test_parsers/test_rst/test_TableParser.py 2024-08-01 22:27:19 UTC (rev 9841)
+++ trunk/docutils/test/test_parsers/test_rst/test_TableParser.py 2024-08-01 22:41:27 UTC (rev 9842)
@@ -23,7 +23,7 @@
class GridTableParserTestCase(unittest.TestCase):
def test_parse_table(self):
parser = tableparser.GridTableParser()
- for name, cases in totest.items():
+ for cases in totest.values():
for case in cases:
case_input, case_table, _case_expected = case
lines_input = StringList(string2lines(case_input), 'test data')
Modified: trunk/docutils/tools/buildhtml.py
===================================================================
--- trunk/docutils/tools/buildhtml.py 2024-08-01 22:27:19 UTC (rev 9841)
+++ trunk/docutils/tools/buildhtml.py 2024-08-01 22:41:27 UTC (rev 9842)
@@ -201,7 +201,7 @@
"""
with warnings.catch_warnings():
warnings.filterwarnings('ignore', category=DeprecationWarning)
- for name, publisher in self.publishers.items():
+ for publisher in self.publishers.values():
option_parser = OptionParser(
components=publisher.components, read_config_files=True,
usage=usage, description=description)
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <aa-...@us...> - 2024-08-01 23:10:30
|
Revision: 9844
http://sourceforge.net/p/docutils/code/9844
Author: aa-turner
Date: 2024-08-01 23:10:27 +0000 (Thu, 01 Aug 2024)
Log Message:
-----------
Remove remaining references to setup.py
Modified Paths:
--------------
trunk/docutils/README.txt
trunk/docutils/docs/dev/policies.txt
Modified: trunk/docutils/README.txt
===================================================================
--- trunk/docutils/README.txt 2024-08-01 22:57:34 UTC (rev 9843)
+++ trunk/docutils/README.txt 2024-08-01 23:10:27 UTC (rev 9844)
@@ -127,7 +127,7 @@
1. Open a shell
- 2. Go to the directory containing the file ``setup.py``.
+ 2. Go to the directory containing the ``pyproject.toml`` file.
3. Install the package with **one** of the following commands::
@@ -245,7 +245,8 @@
* THANKS.txt: List of contributors.
-* setup.py: Installation script. See "Installation" below.
+* pyproject.toml: Project metadata.
+ See "Installation" above.
* docutils: The project source directory, installed as a Python
package.
@@ -295,7 +296,7 @@
Unpack in a temporary directory,
**not** directly in Python's ``site-packages``.
-Continue with the `Installation`_ instructions below.
+See the `Installation`_ instructions above.
__ docs/dev/repository.html#checking-out-the-repository
.. _Docutils version repository: docs/dev/repository.html
Modified: trunk/docutils/docs/dev/policies.txt
===================================================================
--- trunk/docutils/docs/dev/policies.txt 2024-08-01 22:57:34 UTC (rev 9843)
+++ trunk/docutils/docs/dev/policies.txt 2024-08-01 23:10:27 UTC (rev 9844)
@@ -614,8 +614,7 @@
...
tools/ # For front ends etc.
...
- setup.py # Install the component code and tools/ files
- # into the right places.
+ pyproject.toml # Project metadata
userid/ # For *temporary* personal space.
Some sandbox projects are destined to move to the Docutils core once
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <aa-...@us...> - 2024-08-02 01:16:45
|
Revision: 9845
http://sourceforge.net/p/docutils/code/9845
Author: aa-turner
Date: 2024-08-02 01:16:42 +0000 (Fri, 02 Aug 2024)
Log Message:
-----------
Add a new roman numeral implementation
Modified Paths:
--------------
trunk/docutils/HISTORY.txt
Added Paths:
-----------
trunk/docutils/docutils/utils/_roman_numerals.py
trunk/docutils/test/test_utils/test__roman_numerals.py
Modified: trunk/docutils/HISTORY.txt
===================================================================
--- trunk/docutils/HISTORY.txt 2024-08-01 23:10:27 UTC (rev 9844)
+++ trunk/docutils/HISTORY.txt 2024-08-02 01:16:42 UTC (rev 9845)
@@ -128,6 +128,10 @@
- Removed `Reporter.set_conditions()`.
Set attributes via configuration settings or directly.
+* docutils/utils/_roman_numerals.py
+
+ - Added new implementation.
+
* docutils/utils/error_reporting.py
- Removed. Obsolete in Python 3.
Added: trunk/docutils/docutils/utils/_roman_numerals.py
===================================================================
--- trunk/docutils/docutils/utils/_roman_numerals.py (rev 0)
+++ trunk/docutils/docutils/utils/_roman_numerals.py 2024-08-02 01:16:42 UTC (rev 9845)
@@ -0,0 +1,247 @@
+# $Id$
+# Author: Adam Turner.
+# Copyright: This module is placed in the public domain
+# or under the `Zero Clause BSD licence`_,
+# whichever is more permissive.
+#
+# .. _Zero Clause BSD licence: https://opensource.org/license/0BSD
+
+"""Conversion between integers and roman numerals."""
+
+from __future__ import annotations
+
+import sys
+from typing import TYPE_CHECKING, final
+
+if TYPE_CHECKING:
+ from typing import Final, Self
+
+__all__ = (
+ 'MIN',
+ 'MAX',
+ 'RomanNumeral',
+ 'OutOfRangeError',
+ 'InvalidRomanNumeralError',
+)
+
+MIN: Final = 1
+"""The value of the smallest well-formed roman numeral."""
+
+# Note that 4,999 (MMMMCMXCIX) breaks one of the rules of Roman numerals,
+# that the same character may not appear more than thrice consecutively,
+# meaning the largest 'well-formed' Roman numeral is 3,999 (MMMCMXCIX).
+# We use 4,999 for backwards compatibility reasons.
+MAX: Final = 4_999
+"""The value of the largest well-formed roman numeral."""
+
+
+class OutOfRangeError(TypeError):
+ """Number out of range (must be between 1 and 4,999)."""
+
+
+class InvalidRomanNumeralError(ValueError):
+ """Not a valid Roman numeral."""
+
+ def __init__(self, value, *args):
+ msg = f'Invalid Roman numeral: {value}'
+ super().__init__(msg, *args)
+
+
+@final
+class RomanNumeral:
+ """A Roman numeral.
+
+ Only values between 1 and 4,999 are valid.
+ Stores the value internally as an ``int``.
+
+ >>> answer = RomanNumeral(42)
+ >>> print(answer.to_uppercase())
+ XLII
+ """
+ __slots__ = ('_value',)
+ _value: int
+
+ def __init__(self, value: int, /) -> None:
+ if not isinstance(value, int):
+ msg = 'RomanNumeral: an integer is required, not %r'
+ raise TypeError(msg % type(value).__qualname__)
+ if value < MIN or value > MAX:
+ msg = 'Number out of range (must be between 1 and 4,999). Got %s.'
+ raise OutOfRangeError(msg % value)
+ super().__setattr__('_value', value)
+
+ def __int__(self) -> int:
+ return self._value
+
+ def __str__(self) -> str:
+ return self.to_uppercase()
+
+ def __repr__(self):
+ return f'{self.__class__.__name__}({self._value!r})'
+
+ def __eq__(self, other):
+ if isinstance(other, RomanNumeral):
+ return self._value == other._value
+ return NotImplemented
+
+ def __lt__(self, other):
+ if isinstance(other, RomanNumeral):
+ return self._value < other._value
+ return NotImplemented
+
+ def __hash__(self):
+ return hash(self._value)
+
+ def __setattr__(self, key, value):
+ if key == '_value':
+ raise AttributeError('Cannot set the value attribute.')
+ super().__setattr__(key, value)
+
+ def to_uppercase(self) -> str:
+ """Converts a ``RomanNumeral`` to an uppercase string.
+
+ >>> answer = RomanNumeral(42)
+ >>> assert answer.to_uppercase() == 'XLII'
+ """
+ out = []
+ n = int(self)
+ for value, name, _ in _ROMAN_NUMERAL_PREFIXES:
+ while n >= value:
+ n -= value
+ out.append(name)
+ return ''.join(out)
+
+ def to_lowercase(self) -> str:
+ """Converts a ``RomanNumeral`` to a lowercase string.
+
+ >>> answer = RomanNumeral(42)
+ >>> assert answer.to_lowercase() == 'xlii'
+ """
+ out = []
+ n = int(self)
+ for value, _, name in _ROMAN_NUMERAL_PREFIXES:
+ while n >= value:
+ n -= value
+ out.append(name)
+ return ''.join(out)
+
+ @classmethod
+ def from_string(self, string: str, /) -> Self:
+ """Creates a ``RomanNumeral`` from a well-formed string representation.
+
+ Returns ``RomanNumeral`` or raises ``InvalidRomanNumeralError``.
+
+ >>> answer = RomanNumeral.from_string('XLII')
+ >>> assert int(answer) == 42
+ """
+ # Not an empty string.
+ if not string or not isinstance(string, str):
+ raise InvalidRomanNumeralError(string)
+
+ # ASCII-only uppercase string.
+ if string.isascii() and string.isupper():
+ chars = string.encode('ascii')
+ elif string.isascii() and string.islower():
+ chars = string.upper().encode('ascii')
+ else:
+ # Either Non-ASCII or mixed-case ASCII.
+ raise InvalidRomanNumeralError(string)
+
+ # ASCII-only uppercase string only containing I, V, X, L, C, D, M.
+ if not frozenset(b'IVXLCDM').issuperset(chars):
+ raise InvalidRomanNumeralError(string)
+
+ result: int = 0
+ idx: int = 0
+
+ # Thousands: between 0 and 4 "M" characters at the start
+ for _ in range(4):
+ if chars[idx:idx + 1] == b'M':
+ result += 1000
+ idx += 1
+ else:
+ break
+ if len(chars) == idx:
+ return RomanNumeral(result)
+
+ # Hundreds: 900 ("CM"), 400 ("CD"), 0-300 (0 to 3 "C" chars),
+ # or 500-800 ("D", followed by 0 to 3 "C" chars)
+ if chars[idx:idx + 2] == b'CM':
+ result += 900
+ idx += 2
+ elif chars[idx:idx + 2] == b'CD':
+ result += 400
+ idx += 2
+ else:
+ if chars[idx:idx + 1] == b'D':
+ result += 500
+ idx += 1
+ for _ in range(3):
+ if chars[idx:idx + 1] == b'C':
+ result += 100
+ idx += 1
+ else:
+ break
+ if len(chars) == idx:
+ return RomanNumeral(result)
+
+ # Tens: 90 ("XC"), 40 ("XL"), 0-30 (0 to 3 "X" chars),
+ # or 50-80 ("L", followed by 0 to 3 "X" chars)
+ if chars[idx:idx + 2] == b'XC':
+ result += 90
+ idx += 2
+ elif chars[idx:idx + 2] == b'XL':
+ result += 40
+ idx += 2
+ else:
+ if chars[idx:idx + 1] == b'L':
+ result += 50
+ idx += 1
+ for _ in range(3):
+ if chars[idx:idx + 1] == b'X':
+ result += 10
+ idx += 1
+ else:
+ break
+ if len(chars) == idx:
+ return RomanNumeral(result)
+
+ # Ones: 9 ("IX"), 4 ("IV"), 0-3 (0 to 3 "I" chars),
+ # or 5-8 ("V", followed by 0 to 3 "I" chars)
+ if chars[idx:idx + 2] == b'IX':
+ result += 9
+ idx += 2
+ elif chars[idx:idx + 2] == b'IV':
+ result += 4
+ idx += 2
+ else:
+ if chars[idx:idx + 1] == b'V':
+ result += 5
+ idx += 1
+ for _ in range(3):
+ if chars[idx:idx + 1] == b'I':
+ result += 1
+ idx += 1
+ else:
+ break
+ if len(chars) == idx:
+ return RomanNumeral(result)
+ raise InvalidRomanNumeralError(string)
+
+
+_ROMAN_NUMERAL_PREFIXES: Final = [
+ (1000, sys.intern('M'), sys.intern('m')),
+ (900, sys.intern('CM'), sys.intern('cm')),
+ (500, sys.intern('D'), sys.intern('d')),
+ (400, sys.intern('CD'), sys.intern('cd')),
+ (100, sys.intern('C'), sys.intern('c')),
+ (90, sys.intern('XC'), sys.intern('xc')),
+ (50, sys.intern('L'), sys.intern('l')),
+ (40, sys.intern('XL'), sys.intern('xl')),
+ (10, sys.intern('X'), sys.intern('x')),
+ (9, sys.intern('IX'), sys.intern('ix')),
+ (5, sys.intern('V'), sys.intern('v')),
+ (4, sys.intern('IV'), sys.intern('iv')),
+ (1, sys.intern('I'), sys.intern('i')),
+]
+"""Numeral value, uppercase character, and lowercase character."""
Property changes on: trunk/docutils/docutils/utils/_roman_numerals.py
___________________________________________________________________
Added: svn:executable
## -0,0 +1 ##
+*
\ No newline at end of property
Added: trunk/docutils/test/test_utils/test__roman_numerals.py
===================================================================
--- trunk/docutils/test/test_utils/test__roman_numerals.py (rev 0)
+++ trunk/docutils/test/test_utils/test__roman_numerals.py 2024-08-02 01:16:42 UTC (rev 9845)
@@ -0,0 +1,210 @@
+#! /usr/bin/env python3
+
+# $Id$
+# Author: Adam Turner.
+# Copyright: This module is placed in the public domain
+# or under the `Zero Clause BSD licence`_,
+# whichever is more permissive.
+#
+# .. _Zero Clause BSD licence: https://opensource.org/license/0BSD
+
+"""
+Tests for `docutils.utils._roman_numerals`.
+"""
+
+from pathlib import Path
+import sys
+import unittest
+
+if __name__ == '__main__':
+ # prepend the "docutils root" to the Python library path
+ # so we import the local `docutils` package.
+ sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
+
+from docutils.utils._roman_numerals import (
+ MIN,
+ MAX,
+ RomanNumeral,
+ OutOfRangeError,
+ InvalidRomanNumeralError,
+)
+
+
+class NewRomanNumeralTestCase(unittest.TestCase):
+ def test_zero(self) -> None:
+ with self.assertRaises(OutOfRangeError) as ctx:
+ RomanNumeral(0)
+ msg = str(ctx.exception)
+ self.assertEqual(
+ msg,
+ 'Number out of range (must be between 1 and 4,999). Got 0.',
+ )
+
+ def test_one(self) -> None:
+ self.assertEqual(int(RomanNumeral(1)), 1)
+
+ def test_MIN(self) -> None:
+ self.assertEqual(int(RomanNumeral(MIN)), MIN)
+
+ def test_forty_two(self) -> None:
+ self.assertEqual(int(RomanNumeral(42)), 42)
+
+ def test_four_thousand_nine_hundred_and_ninety_nine(self) -> None:
+ self.assertEqual(int(RomanNumeral(4_999)), 4_999)
+
+ def test_MAX(self) -> None:
+ self.assertEqual(int(RomanNumeral(MAX)), MAX)
+
+ def test_five_thousand(self) -> None:
+ with self.assertRaises(OutOfRangeError) as ctx:
+ RomanNumeral(5_000)
+ msg = str(ctx.exception)
+ self.assertEqual(
+ msg,
+ 'Number out of range (must be between 1 and 4,999). Got 5000.',
+ )
+
+ def test_minus_one(self) -> None:
+ with self.assertRaises(OutOfRangeError) as ctx:
+ RomanNumeral(-1)
+ msg = str(ctx.exception)
+ self.assertEqual(
+ msg,
+ 'Number out of range (must be between 1 and 4,999). Got -1.',
+ )
+
+ def test_float(self) -> None:
+ with self.assertRaises(TypeError) as ctx:
+ RomanNumeral(4.2)
+ msg = str(ctx.exception)
+ self.assertEqual(
+ msg,
+ "RomanNumeral: an integer is required, not 'float'",
+ )
+
+
+class ToStringTestCase(unittest.TestCase):
+ def test_str(self):
+ test_numerals = [
+ 'I', 'II', 'III', 'IV', 'V',
+ 'VI', 'VII', 'VIII', 'IX', 'X',
+ 'XI', 'XII', 'XIII', 'XIV', 'XV',
+ 'XVI', 'XVII', 'XVIII', 'XIX', 'XX',
+ 'XXI', 'XXII', 'XXIII', 'XXIV',
+ ]
+ for n, roman_str in enumerate(test_numerals, start=1):
+ with self.subTest(id=n, roman_str=roman_str):
+ num = RomanNumeral(n)
+ self.assertEqual(f'{num}', roman_str)
+
+ def test_uppercase(self):
+ test_numerals = [
+ 'I', 'II', 'III', 'IV', 'V',
+ 'VI', 'VII', 'VIII', 'IX', 'X',
+ 'XI', 'XII', 'XIII', 'XIV', 'XV',
+ 'XVI', 'XVII', 'XVIII', 'XIX', 'XX',
+ 'XXI', 'XXII', 'XXIII', 'XXIV',
+ ]
+ for n, roman_str in enumerate(test_numerals, start=1):
+ with self.subTest(id=n, roman_str=roman_str):
+ num = RomanNumeral(n)
+ self.assertEqual(num.to_uppercase(), roman_str)
+
+ def test_lowercase(self):
+ test_numerals = [
+ 'i', 'ii', 'iii', 'iv', 'v',
+ 'vi', 'vii', 'viii', 'ix', 'x',
+ 'xi', 'xii', 'xiii', 'xiv', 'xv',
+ 'xvi', 'xvii', 'xviii', 'xix', 'xx',
+ 'xxi', 'xxii', 'xxiii', 'xxiv',
+ ]
+ for n, roman_str in enumerate(test_numerals, start=1):
+ with self.subTest(id=n, roman_str=roman_str):
+ num = RomanNumeral(n)
+ self.assertEqual(num.to_lowercase(), roman_str)
+
+ def test_minitrue(self):
+ # IGNORANCE IS STRENGTH
+ num = RomanNumeral(1984)
+ self.assertEqual(f'{num}', 'MCMLXXXIV')
+ self.assertEqual(num.to_uppercase(), 'MCMLXXXIV')
+ self.assertEqual(num.to_lowercase(), 'mcmlxxxiv')
+
+
+class FromStringTestCase(unittest.TestCase):
+ def test_uppercase(self):
+ test_numerals = [
+ 'I', 'II', 'III', 'IV', 'V',
+ 'VI', 'VII', 'VIII', 'IX', 'X',
+ 'XI', 'XII', 'XIII', 'XIV', 'XV',
+ 'XVI', 'XVII', 'XVIII', 'XIX', 'XX',
+ 'XXI', 'XXII', 'XXIII', 'XXIV',
+ ]
+ for n, roman_str in enumerate(test_numerals, start=1):
+ with self.subTest(id=n, roman_str=roman_str):
+ expected = RomanNumeral(n)
+ parsed = RomanNumeral.from_string(roman_str)
+ self.assertEqual(expected, parsed)
+
+ def test_lowercase(self):
+ test_numerals = [
+ 'i', 'ii', 'iii', 'iv', 'v',
+ 'vi', 'vii', 'viii', 'ix', 'x',
+ 'xi', 'xii', 'xiii', 'xiv', 'xv',
+ 'xvi', 'xvii', 'xviii', 'xix', 'xx',
+ 'xxi', 'xxii', 'xxiii', 'xxiv',
+ ]
+ for n, roman_str in enumerate(test_numerals, start=1):
+ with self.subTest(id=n, roman_str=roman_str):
+ expected = RomanNumeral(n)
+ parsed = RomanNumeral.from_string(roman_str)
+ self.assertEqual(expected, parsed)
+
+ def test_special(self):
+ parsed = RomanNumeral.from_string('MDCCCXXIII')
+ self.assertEqual(RomanNumeral(1823), parsed)
+
+ parsed = RomanNumeral.from_string('mdcccxxiii')
+ self.assertEqual(RomanNumeral(1823), parsed)
+
+ parsed = RomanNumeral.from_string('MCMLXXXIV')
+ self.assertEqual(RomanNumeral(1984), parsed)
+
+ parsed = RomanNumeral.from_string('mcmlxxxiv')
+ self.assertEqual(RomanNumeral(1984), parsed)
+
+ parsed = RomanNumeral.from_string('MM')
+ self.assertEqual(RomanNumeral(2000), parsed)
+
+ parsed = RomanNumeral.from_string('mm')
+ self.assertEqual(RomanNumeral(2000), parsed)
+
+ parsed = RomanNumeral.from_string('MMMMCMXCIX')
+ self.assertEqual(RomanNumeral(4_999), parsed)
+
+ parsed = RomanNumeral.from_string('mmmmcmxcix')
+ self.assertEqual(RomanNumeral(4_999), parsed)
+
+ def test_invalid(self):
+ with self.assertRaises(InvalidRomanNumeralError) as ctx:
+ RomanNumeral.from_string('Not a Roman numeral!')
+ msg = str(ctx.exception)
+ self.assertEqual(msg, 'Invalid Roman numeral: Not a Roman numeral!')
+
+ def test_mixed_case(self):
+ with self.assertRaises(InvalidRomanNumeralError) as ctx:
+ RomanNumeral.from_string('McMlXxXiV')
+ msg = str(ctx.exception)
+ self.assertEqual(msg, 'Invalid Roman numeral: McMlXxXiV')
+
+
+class RoundTripTestCase(unittest.TestCase):
+ def test_round_trip(self):
+ for n in range(MIN, MAX + 1, 19):
+ num = RomanNumeral(n)
+ parsed = RomanNumeral.from_string(str(num))
+ self.assertEqual(num, parsed)
+
+
+if __name__ == '__main__':
+ unittest.main()
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <aa-...@us...> - 2024-08-02 01:36:20
|
Revision: 9846
http://sourceforge.net/p/docutils/code/9846
Author: aa-turner
Date: 2024-08-02 01:36:18 +0000 (Fri, 02 Aug 2024)
Log Message:
-----------
Adopt ``RomanNumeral``
Modified Paths:
--------------
trunk/docutils/docutils/parsers/rst/states.py
trunk/docutils/docutils/utils/_roman_numerals.py
trunk/docutils/docutils/writers/latex2e/__init__.py
trunk/docutils/docutils/writers/manpage.py
trunk/docutils/test/test_utils/test__roman_numerals.py
Modified: trunk/docutils/docutils/parsers/rst/states.py
===================================================================
--- trunk/docutils/docutils/parsers/rst/states.py 2024-08-02 01:16:42 UTC (rev 9845)
+++ trunk/docutils/docutils/parsers/rst/states.py 2024-08-02 01:36:18 UTC (rev 9846)
@@ -114,8 +114,12 @@
import docutils.parsers.rst
from docutils.parsers.rst import directives, languages, tableparser, roles
from docutils.utils import escape2null, column_width
-from docutils.utils import punctuation_chars, roman, urischemes
+from docutils.utils import punctuation_chars, urischemes
from docutils.utils import split_escaped_whitespace
+from docutils.utils._roman_numerals import (
+ InvalidRomanNumeralError,
+ RomanNumeral,
+)
class MarkupError(DataError): pass
@@ -1067,10 +1071,6 @@
return ord(s) - _zero
-def _lowerroman_to_int(s):
- return roman.fromRoman(s.upper())
-
-
class Body(RSTState):
"""
@@ -1098,8 +1098,8 @@
enum.converters = {'arabic': int,
'loweralpha': _loweralpha_to_int,
'upperalpha': _upperalpha_to_int,
- 'lowerroman': _lowerroman_to_int,
- 'upperroman': roman.fromRoman}
+ 'lowerroman': RomanNumeral.from_string,
+ 'upperroman': RomanNumeral.from_string}
enum.sequenceregexps = {}
for sequence in enum.sequences:
@@ -1382,8 +1382,8 @@
ordinal = 1
else:
try:
- ordinal = self.enum.converters[sequence](text)
- except roman.InvalidRomanNumeralError:
+ ordinal = int(self.enum.converters[sequence](text))
+ except InvalidRomanNumeralError:
ordinal = None
return format, sequence, text, ordinal
@@ -1433,8 +1433,8 @@
enumerator = chr(ordinal + ord('a') - 1)
elif sequence.endswith('roman'):
try:
- enumerator = roman.toRoman(ordinal)
- except roman.RomanError:
+ enumerator = RomanNumeral(ordinal).to_uppercase()
+ except TypeError:
return None
else: # shouldn't happen
raise ParserError('unknown enumerator sequence: "%s"'
Modified: trunk/docutils/docutils/utils/_roman_numerals.py
===================================================================
--- trunk/docutils/docutils/utils/_roman_numerals.py 2024-08-02 01:16:42 UTC (rev 9845)
+++ trunk/docutils/docutils/utils/_roman_numerals.py 2024-08-02 01:36:18 UTC (rev 9846)
@@ -1,5 +1,5 @@
# $Id$
-# Author: Adam Turner.
+# Author: Adam Turner.
# Copyright: This module is placed in the public domain
# or under the `Zero Clause BSD licence`_,
# whichever is more permissive.
Modified: trunk/docutils/docutils/writers/latex2e/__init__.py
===================================================================
--- trunk/docutils/docutils/writers/latex2e/__init__.py 2024-08-02 01:16:42 UTC (rev 9845)
+++ trunk/docutils/docutils/writers/latex2e/__init__.py 2024-08-02 01:36:18 UTC (rev 9846)
@@ -17,13 +17,10 @@
import string
from urllib.request import url2pathname
import warnings
-try:
- import roman
-except ImportError:
- import docutils.utils.roman as roman
from docutils import frontend, nodes, languages, writers, utils
from docutils.transforms import writer_aux
+from docutils.utils._roman_numerals import RomanNumeral
from docutils.utils.math import pick_math_environment, unichar2tex
LATEX_WRITER_DIR = Path(__file__).parent
@@ -2196,7 +2193,7 @@
suffix = node.get('suffix', '.')
enum_level = len(self._enumeration_counters)+1
- counter_name = 'enum' + roman.toRoman(enum_level).lower()
+ counter_name = 'enum' + RomanNumeral(enum_level).to_lowercase()
label = r'%s\%s{%s}%s' % (prefix, enumtype, counter_name, suffix)
self._enumeration_counters.append(label)
@@ -3139,13 +3136,13 @@
# section level not supported by LaTeX
if self.settings.legacy_class_functions:
self.fallbacks['title'] = PreambleCmds.title_legacy
- section_name += '[section%s]' % roman.toRoman(level)
+ section_name += '[section%s]' % RomanNumeral(level)
else:
if not self.fallback_stylesheet:
self.fallbacks['title'] = PreambleCmds.title
self.fallbacks['DUclass'] = PreambleCmds.duclass
self.out.append('\\begin{DUclass}{section%s}\n'
- % roman.toRoman(level))
+ % RomanNumeral(level))
# System messages heading in red:
if 'system-messages' in node.parent['classes']:
Modified: trunk/docutils/docutils/writers/manpage.py
===================================================================
--- trunk/docutils/docutils/writers/manpage.py 2024-08-02 01:16:42 UTC (rev 9845)
+++ trunk/docutils/docutils/writers/manpage.py 2024-08-02 01:36:18 UTC (rev 9846)
@@ -47,10 +47,7 @@
import docutils
from docutils import frontend, nodes, writers, languages
-try:
- import roman
-except ImportError:
- from docutils.utils import roman
+from docutils.utils._roman_numerals import RomanNumeral
FIELD_LIST_INDENT = 7
DEFINITION_LIST_INDENT = 7
@@ -408,10 +405,11 @@
if self._style in ('loweralpha', 'upperalpha'):
return "%c." % self._cnt
if self._style.endswith('roman'):
- res = roman.toRoman(self._cnt) + '.'
+ res = RomanNumeral(self._cnt)
if self._style.startswith('upper'):
- return res.upper()
- return res.lower()
+ return res.to_uppercase() + '.'
+ else:
+ return res.to_lowercase() + '.'
# else 'arabic', ...
return "%d." % self._cnt
Modified: trunk/docutils/test/test_utils/test__roman_numerals.py
===================================================================
--- trunk/docutils/test/test_utils/test__roman_numerals.py 2024-08-02 01:16:42 UTC (rev 9845)
+++ trunk/docutils/test/test_utils/test__roman_numerals.py 2024-08-02 01:36:18 UTC (rev 9846)
@@ -1,7 +1,7 @@
#! /usr/bin/env python3
# $Id$
-# Author: Adam Turner.
+# Author: Adam Turner.
# Copyright: This module is placed in the public domain
# or under the `Zero Clause BSD licence`_,
# whichever is more permissive.
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mi...@us...> - 2024-08-07 14:05:28
|
Revision: 9861
http://sourceforge.net/p/docutils/code/9861
Author: milde
Date: 2024-08-07 14:05:25 +0000 (Wed, 07 Aug 2024)
Log Message:
-----------
Formatting, simplifications, and fixes for ``frontend.py``.
Remove obsolete method `OptionParser.set_defaults_from_dict()`.
The `pathdict` in `make_paths_absolute()` now works with
values that are tuples of path names (``dict[str, tuple[_FsPath]``).
Use an alias for "file system path" type (str or PathLike).
Line up closing bracket with content (as usual in Docutils).
Close sequences that are unlikely to be extended in another version
on the same line.
Modified Paths:
--------------
trunk/docutils/RELEASE-NOTES.txt
trunk/docutils/docutils/frontend.py
Modified: trunk/docutils/RELEASE-NOTES.txt
===================================================================
--- trunk/docutils/RELEASE-NOTES.txt 2024-08-07 12:12:29 UTC (rev 9860)
+++ trunk/docutils/RELEASE-NOTES.txt 2024-08-07 14:05:25 UTC (rev 9861)
@@ -235,6 +235,8 @@
Removed objects
`docutils.core.Publisher.setup_option_parser()`
internal, obsolete,
+ `docutils.frontend.OptionParser.set_defaults_from_dict()`
+ obsolete,
`docutils.nodes.Element.set_class()`
obsolete, append to Element['classes'] directly,
`docutils.parsers.rst.directives.tables.CSVTable.decode_from_csv()`
Modified: trunk/docutils/docutils/frontend.py
===================================================================
--- trunk/docutils/docutils/frontend.py 2024-08-07 12:12:29 UTC (rev 9860)
+++ trunk/docutils/docutils/frontend.py 2024-08-07 14:05:25 UTC (rev 9861)
@@ -75,8 +75,10 @@
from docutils import SettingsSpec, _OptionTuple, _SettingsSpecTuple
+ _FsPath = str | os.PathLike[str]
+
class _OptionValidator(Protocol):
- def __call__( # NoQA: E704
+ def __call__(
self,
setting: str,
value: str | None,
@@ -84,13 +86,17 @@
/,
config_parser: ConfigParser | None = None,
config_section: str | None = None,
- ) -> Any: ...
+ ) -> Any:
+ ...
-def store_multiple(
- option: optparse.Option, opt: str, value: Any, parser: OptionParser,
- *args: str, **kwargs: Any,
-) -> None:
+def store_multiple(option: optparse.Option,
+ opt: str,
+ value: Any,
+ parser: OptionParser,
+ *args: str,
+ **kwargs: Any,
+ ) -> None:
"""
Store multiple values in `parser.values`. (Option callback.)
@@ -103,9 +109,11 @@
setattr(parser.values, key, value)
-def read_config_file(
- option: optparse.Option, opt: str, value: Any, parser: OptionParser,
-) -> None:
+def read_config_file(option: optparse.Option,
+ opt: str,
+ value: Any,
+ parser: OptionParser,
+ ) -> None:
"""
Read a configuration file during option processing. (Option callback.)
"""
@@ -116,13 +124,12 @@
parser.values.update(new_settings, parser)
-def validate_encoding(
- setting: str,
- value: str | None = None,
- option_parser: OptionParser | None = None,
- config_parser: ConfigParser | None = None,
- config_section: str | None = None,
-) -> str | None:
+def validate_encoding(setting: str,
+ value: str | None = None,
+ option_parser: OptionParser | None = None,
+ config_parser: ConfigParser | None = None,
+ config_section: str | None = None,
+ ) -> str | None:
# All arguments except `value` are ignored
# (kept for compatibility with "optparse" module).
# If there is only one positional argument, it is interpreted as `value`.
@@ -141,12 +148,12 @@
def validate_encoding_error_handler(
- setting: str,
- value: str | None = None,
- option_parser: OptionParser | None = None,
- config_parser: ConfigParser | None = None,
- config_section: str | None = None,
-) -> str:
+ setting: str,
+ value: str | None = None,
+ option_parser: OptionParser | None = None,
+ config_parser: ConfigParser | None = None,
+ config_section: str | None = None,
+ ) -> str:
# All arguments except `value` are ignored
# (kept for compatibility with "optparse" module).
# If there is only one positional argument, it is interpreted as `value`.
@@ -164,15 +171,20 @@
def validate_encoding_and_error_handler(
- setting: str,
- value: str | None = None,
- option_parser: OptionParser | None = None,
- config_parser: ConfigParser | None = None,
- config_section: str | None = None,
-) -> str:
- """
+ setting: str,
+ value: str | None = None,
+ option_parser: OptionParser | None = None,
+ config_parser: ConfigParser | None = None,
+ config_section: str | None = None,
+ ) -> str:
+ """Check/normalize encoding settings
+
Side-effect: if an error handler is included in the value, it is inserted
into the appropriate place as if it were a separate setting/option.
+
+ All arguments except `value` are ignored
+ (kept for compatibility with "optparse" module).
+ If there is only one positional argument, it is interpreted as `value`.
"""
if ':' in value:
encoding, handler = value.split(':')
@@ -187,17 +199,17 @@
return validate_encoding(encoding)
-def validate_boolean(
- setting: str | bool,
- value: str | None = None,
- option_parser: OptionParser | None = None,
- config_parser: ConfigParser | None = None,
- config_section: str | None = None,
-) -> bool:
+def validate_boolean(setting: str | bool,
+ value: str | None = None,
+ option_parser: OptionParser | None = None,
+ config_parser: ConfigParser | None = None,
+ config_section: str | None = None,
+ ) -> bool:
"""Check/normalize boolean settings:
- True: '1', 'on', 'yes', 'true'
- False: '0', 'off', 'no','false', ''
+ :True: '1', 'on', 'yes', 'true'
+ :False: '0', 'off', 'no','false', ''
+
All arguments except `value` are ignored
(kept for compatibility with "optparse" module).
If there is only one positional argument, it is interpreted as `value`.
@@ -212,18 +224,18 @@
raise LookupError('unknown boolean value: "%s"' % value)
-def validate_ternary(
- setting: str | bool,
- value: str | None = None,
- option_parser: OptionParser | None = None,
- config_parser: ConfigParser | None = None,
- config_section: str | None = None,
-) -> str | bool | None:
+def validate_ternary(setting: str | bool,
+ value: str | None = None,
+ option_parser: OptionParser | None = None,
+ config_parser: ConfigParser | None = None,
+ config_section: str | None = None,
+ ) -> str | bool | None:
"""Check/normalize three-value settings:
- True: '1', 'on', 'yes', 'true'
- False: '0', 'off', 'no','false', ''
- any other value: returned as-is.
+ :True: '1', 'on', 'yes', 'true'
+ :False: '0', 'off', 'no','false', ''
+ :any other value: returned as-is.
+
All arguments except `value` are ignored
(kept for compatibility with "optparse" module).
If there is only one positional argument, it is interpreted as `value`.
@@ -238,13 +250,12 @@
return value
-def validate_nonnegative_int(
- setting: str,
- value: str | None = None,
- option_parser: OptionParser | None = None,
- config_parser: ConfigParser | None = None,
- config_section: str | None = None,
-) -> int:
+def validate_nonnegative_int(setting: str | int,
+ value: str | None = None,
+ option_parser: OptionParser | None = None,
+ config_parser: ConfigParser | None = None,
+ config_section: str | None = None,
+ ) -> int:
# All arguments except `value` are ignored
# (kept for compatibility with "optparse" module).
# If there is only one positional argument, it is interpreted as `value`.
@@ -256,13 +267,12 @@
return value
-def validate_threshold(
- setting: str,
- value: str | None = None,
- option_parser: OptionParser | None = None,
- config_parser: ConfigParser | None = None,
- config_section: str | None = None,
-) -> int:
+def validate_threshold(setting: str | int,
+ value: str | None = None,
+ option_parser: OptionParser | None = None,
+ config_parser: ConfigParser | None = None,
+ config_section: str | None = None,
+ ) -> int:
# All arguments except `value` are ignored
# (kept for compatibility with "optparse" module).
# If there is only one positional argument, it is interpreted as `value`.
@@ -278,12 +288,12 @@
def validate_colon_separated_string_list(
- setting: str | list[str],
- value: str | None = None,
- option_parser: OptionParser | None = None,
- config_parser: ConfigParser | None = None,
- config_section: str | None = None,
-) -> list[str]:
+ setting: str | list[str],
+ value: str | None = None,
+ option_parser: OptionParser | None = None,
+ config_parser: ConfigParser | None = None,
+ config_section: str | None = None,
+ ) -> list[str]:
# All arguments except `value` are ignored
# (kept for compatibility with "optparse" module).
# If there is only one positional argument, it is interpreted as `value`.
@@ -298,12 +308,12 @@
def validate_comma_separated_list(
- setting: str | list[str] | list[str | tuple[str, str]],
- value: str | None = None,
- option_parser: OptionParser | None = None,
- config_parser: ConfigParser | None = None,
- config_section: str | None = None,
-) -> list[str]:
+ setting: str | list[str],
+ value: str | None = None,
+ option_parser: OptionParser | None = None,
+ config_parser: ConfigParser | None = None,
+ config_section: str | None = None,
+ ) -> list[str]:
"""Check/normalize list arguments (split at "," and strip whitespace).
All arguments except `value` are ignored
@@ -324,13 +334,12 @@
return value
-def validate_math_output(
- setting: str,
- value: str | None = None,
- option_parser: OptionParser | None = None,
- config_parser: ConfigParser | None = None,
- config_section: str | None = None,
-) -> tuple[()] | tuple[str, str]:
+def validate_math_output(setting: str,
+ value: str | None = None,
+ option_parser: OptionParser | None = None,
+ config_parser: ConfigParser | None = None,
+ config_section: str | None = None,
+ ) -> tuple[()] | tuple[str, str]:
"""Check "math-output" setting, return list with "format" and "options".
See also https://docutils.sourceforge.io/docs/user/config.html#math-output
@@ -365,13 +374,12 @@
return format, options
-def validate_url_trailing_slash(
- setting: str | None,
- value: str | None = None,
- option_parser: OptionParser | None = None,
- config_parser: ConfigParser | None = None,
- config_section: str | None = None,
-) -> str:
+def validate_url_trailing_slash(setting: str | None,
+ value: str | None = None,
+ option_parser: OptionParser | None = None,
+ config_parser: ConfigParser | None = None,
+ config_section: str | None = None,
+ ) -> str:
# All arguments except `value` are ignored
# (kept for compatibility with "optparse" module).
# If there is only one positional argument, it is interpreted as `value`.
@@ -385,13 +393,12 @@
return value + '/'
-def validate_dependency_file(
- setting: str | None,
- value: str | None = None,
- option_parser: OptionParser | None = None,
- config_parser: ConfigParser | None = None,
- config_section: str | None = None,
-) -> utils.DependencyList:
+def validate_dependency_file(setting: str | None,
+ value: str | None = None,
+ option_parser: OptionParser | None = None,
+ config_parser: ConfigParser | None = None,
+ config_section: str | None = None,
+ ) -> utils.DependencyList:
# All arguments except `value` are ignored
# (kept for compatibility with "optparse" module).
# If there is only one positional argument, it is interpreted as `value`.
@@ -404,13 +411,12 @@
return utils.DependencyList(None)
-def validate_strip_class(
- setting: str,
- value: str | None = None,
- option_parser: OptionParser | None = None,
- config_parser: ConfigParser | None = None,
- config_section: str | None = None,
-) -> list[str]:
+def validate_strip_class(setting: str,
+ value: str | None = None,
+ option_parser: OptionParser | None = None,
+ config_parser: ConfigParser | None = None,
+ config_section: str | None = None,
+ ) -> list[str]:
# All arguments except `value` are ignored
# (kept for compatibility with "optparse" module).
# If there is only one positional argument, it is interpreted as `value`.
@@ -428,12 +434,12 @@
def validate_smartquotes_locales(
- setting: str | list[str | tuple[str, str]],
- value: str | None = None,
- option_parser: OptionParser | None = None,
- config_parser: ConfigParser | None = None,
- config_section: str | None = None,
-) -> list[tuple[str, Sequence[str]]]:
+ setting: str | list[str | tuple[str, str]],
+ value: str | None = None,
+ option_parser: OptionParser | None = None,
+ config_parser: ConfigParser | None = None,
+ config_section: str | None = None,
+ ) -> list[tuple[str, Sequence[str]]]:
"""Check/normalize a comma separated list of smart quote definitions.
Return a list of (language-tag, quotes) string tuples.
@@ -473,11 +479,10 @@
return lc_quotes
-def make_paths_absolute(
- pathdict: dict[str, list[str | os.PathLike[str]] | str | os.PathLike[str]],
- keys: list[str],
- base_path: str | os.PathLike[str] | None = None,
-) -> None:
+def make_paths_absolute(pathdict: dict[str, list[_FsPath] | _FsPath],
+ keys: tuple[str],
+ base_path: _FsPath | None = None,
+ ) -> None:
"""
Interpret filesystem path settings relative to the `base_path` given.
@@ -493,16 +498,14 @@
for key in keys:
if key in pathdict:
value = pathdict[key]
- if isinstance(value, list):
- value = [str((base_path/path).resolve()) for path in value]
+ if isinstance(value, (list, tuple)):
+ value = (str((base_path/path).resolve()) for path in value)
elif value:
value = str((base_path/value).resolve())
pathdict[key] = value
-def make_one_path_absolute(
- base_path: str | os.PathLike[str], path: str | os.PathLike[str],
-) -> str:
+def make_one_path_absolute(base_path: _FsPath, path: _FsPath) -> str:
# deprecated, will be removed
warnings.warn('frontend.make_one_path_absolute() will be removed '
'in Docutils 0.23.', DeprecationWarning, stacklevel=2)
@@ -509,11 +512,10 @@
return os.path.abspath(os.path.join(base_path, path))
-def filter_settings_spec(
- settings_spec: _SettingsSpecTuple,
- *exclude: str,
- **replace: _OptionTuple,
-) -> _SettingsSpecTuple:
+def filter_settings_spec(settings_spec: _SettingsSpecTuple,
+ *exclude: str,
+ **replace: _OptionTuple,
+ ) -> _SettingsSpecTuple:
"""Return a copy of `settings_spec` excluding/replacing some settings.
`settings_spec` is a tuple of configuration settings
@@ -560,11 +562,10 @@
# Set up dummy dependency list.
self.record_dependencies = utils.DependencyList()
- def update(
- self,
- other_dict: Values | Mapping[str, Any],
- option_parser: OptionParser,
- ) -> None:
+ def update(self,
+ other_dict: Values | Mapping[str, Any],
+ option_parser: OptionParser,
+ ) -> None:
if isinstance(other_dict, Values):
other_dict = other_dict.__dict__
other_dict = dict(other_dict) # also works with ConfigParser sections
@@ -609,9 +610,12 @@
DeprecationWarning, stacklevel=2)
super().__init__(*args, **kwargs)
- def process(
- self, opt: str, value: Any, values: Values, parser: OptionParser,
- ) -> int:
+ def process(self,
+ opt: str,
+ value: Any,
+ values: Values,
+ parser: OptionParser,
+ ) -> int:
"""
Call the validator function on applicable settings and
evaluate the 'overrides' option.
@@ -659,27 +663,23 @@
Filenames will be tilde-expanded later. Later files override earlier ones.
"""
- threshold_choices: ClassVar[list[str]] = [
- 'info', '1', 'warning', '2', 'error', '3', 'severe', '4', 'none', '5',
- ]
+ threshold_choices: ClassVar[tuple[str]] = (
+ 'info', '1', 'warning', '2', 'error', '3', 'severe', '4', 'none', '5')
"""Possible inputs for for --report and --halt threshold values."""
thresholds: ClassVar[dict[str, int]] = {
- 'info': 1, 'warning': 2, 'error': 3, 'severe': 4, 'none': 5,
- }
+ 'info': 1, 'warning': 2, 'error': 3, 'severe': 4, 'none': 5}
"""Lookup table for --report and --halt threshold values."""
booleans: ClassVar[dict[str, bool]] = {
'1': True, 'on': True, 'yes': True, 'true': True,
- '0': False, 'off': False, 'no': False, 'false': False, '': False,
- }
+ '0': False, 'off': False, 'no': False, 'false': False, '': False}
"""Lookup table for boolean configuration file settings."""
default_error_encoding: ClassVar[str] = (
getattr(sys.stderr, 'encoding', None)
or io._locale_encoding
- or 'ascii'
- )
+ or 'ascii')
default_error_encoding_error_handler: ClassVar[str] = 'backslashreplace'
@@ -877,18 +877,16 @@
docutils.__version__,
(details := docutils.__version_details__) and f' [{details}]' or '',
sys.version.split()[0],
- sys.platform,
- )
+ sys.platform)
"""Default version message."""
- def __init__(
- self,
- components: Iterable[SettingsSpec] = (),
- defaults: Mapping[str, Any] | None = None,
- read_config_files: bool | None = False,
- *args,
- **kwargs,
- ) -> None:
+ def __init__(self,
+ components: Iterable[SettingsSpec] = (),
+ defaults: Mapping[str, Any] | None = None,
+ read_config_files: bool | None = False,
+ *args,
+ **kwargs,
+ ) -> None:
"""Set up OptionParser instance.
`components` is a list of Docutils components each containing a
@@ -923,9 +921,8 @@
self.error(str(err))
self.defaults.update(config_settings.__dict__)
- def populate_from_components(
- self, components: Iterable[SettingsSpec],
- ) -> None:
+ def populate_from_components(self, components: Iterable[SettingsSpec],
+ ) -> None:
"""Collect settings specification from components.
For each component, populate from the `SettingsSpec.settings_spec`
@@ -957,7 +954,7 @@
self.defaults.update(component.settings_default_overrides)
@classmethod
- def get_standard_config_files(cls) -> Sequence[str | os.PathLike[str]]:
+ def get_standard_config_files(cls) -> Sequence[_FsPath]:
"""Return list of config files, from environment or standard."""
if 'DOCUTILSCONFIG' in os.environ:
config_files = os.environ['DOCUTILSCONFIG'].split(os.pathsep)
@@ -993,7 +990,7 @@
if config_parser.has_section(section):
settings.update(config_parser[section], self)
make_paths_absolute(settings.__dict__,
- list(self.relative_path_settings),
+ self.relative_path_settings,
os.path.dirname(config_file))
return settings.__dict__
@@ -1000,7 +997,7 @@
def check_values(self, values: Values, args: list[str]) -> Values:
"""Store positional arguments as runtime settings."""
values._source, values._destination = self.check_args(args)
- make_paths_absolute(values.__dict__, list(self.relative_path_settings))
+ make_paths_absolute(values.__dict__, self.relative_path_settings)
values._config_files = self.config_files
return values
@@ -1021,13 +1018,6 @@
'destination. It will clobber the source file.')
return source, destination
- def set_defaults_from_dict(self, defaults: dict[str, Any]) -> None:
- # deprecated, will be removed
- warnings.warn('OptionParser.set_defaults_from_dict() will be removed '
- 'in Docutils 0.22 or with the switch to ArgumentParser.',
- DeprecationWarning, stacklevel=2)
- self.defaults.update(defaults)
-
def get_default_values(self) -> Values:
"""Needed to get custom `Values` instances."""
with warnings.catch_warnings():
@@ -1086,11 +1076,10 @@
Skipping "%s" configuration file.
"""
- def read(
- self,
- filenames: str | Sequence[str],
- option_parser: OptionParser | None = None,
- ) -> list[str]:
+ def read(self,
+ filenames: str | Sequence[str],
+ option_parser: OptionParser | None = None,
+ ) -> list[str]:
# Currently, if a `docutils.frontend.OptionParser` instance is
# supplied, setting values are validated.
if option_parser is not None:
@@ -1132,9 +1121,8 @@
self.set(section, setting, value)
self.remove_section('options')
- def validate_settings(
- self, filename: str, option_parser: OptionParser,
- ) -> None:
+ def validate_settings(self, filename: str, option_parser: OptionParser,
+ ) -> None:
"""
Call the validator function and implement overrides on all applicable
settings.
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <aa-...@us...> - 2024-08-09 04:51:58
|
Revision: 9870
http://sourceforge.net/p/docutils/code/9870
Author: aa-turner
Date: 2024-08-09 04:51:55 +0000 (Fri, 09 Aug 2024)
Log Message:
-----------
Fix Ruff
Modified Paths:
--------------
trunk/docutils/.ruff.toml
trunk/docutils/docutils/parsers/rst/directives/admonitions.py
trunk/docutils/test/test_io.py
Modified: trunk/docutils/.ruff.toml
===================================================================
--- trunk/docutils/.ruff.toml 2024-08-08 21:03:15 UTC (rev 9869)
+++ trunk/docutils/.ruff.toml 2024-08-09 04:51:55 UTC (rev 9870)
@@ -32,6 +32,7 @@
]
ignore = [
"E226", # missing whitespace around arithmetic operator
+ "E227", # "missing whitespace around bitwise or shift operator"
"E228", # missing whitespace around modulo operator
# not generally frowned on by PEP 8:
# "If operators with different priorities are used, consider adding
Modified: trunk/docutils/docutils/parsers/rst/directives/admonitions.py
===================================================================
--- trunk/docutils/docutils/parsers/rst/directives/admonitions.py 2024-08-08 21:03:15 UTC (rev 9869)
+++ trunk/docutils/docutils/parsers/rst/directives/admonitions.py 2024-08-09 04:51:55 UTC (rev 9870)
@@ -96,6 +96,6 @@
node_class = nodes.tip
-class Warning(BaseAdmonition): # NoQA: A001 (overwrite builtin "Warning")
+class Warning(BaseAdmonition): # NoQA: A001 (builtin name)
node_class = nodes.warning
Modified: trunk/docutils/test/test_io.py
===================================================================
--- trunk/docutils/test/test_io.py 2024-08-08 21:03:15 UTC (rev 9869)
+++ trunk/docutils/test/test_io.py 2024-08-09 04:51:55 UTC (rev 9870)
@@ -31,7 +31,7 @@
SUPPRESS_ENCODING_WARNING = sys.flags.warn_default_encoding
else:
SUPPRESS_ENCODING_WARNING = False
- EncodingWarning = UnicodeWarning
+ EncodingWarning = UnicodeWarning # NoQA: A001 (builtin name)
# DATA_ROOT is ./test/data/ from the docutils root
DATA_ROOT = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'data')
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <aa-...@us...> - 2024-08-09 07:52:39
|
Revision: 9877
http://sourceforge.net/p/docutils/code/9877
Author: aa-turner
Date: 2024-08-09 07:52:36 +0000 (Fri, 09 Aug 2024)
Log Message:
-----------
Move unused ``version_identifier()`` to a test helper
Modified Paths:
--------------
trunk/docutils/docutils/utils/__init__.py
trunk/docutils/test/test__init__.py
trunk/docutils/test/test_utils/test__init__.py
Modified: trunk/docutils/docutils/utils/__init__.py
===================================================================
--- trunk/docutils/docutils/utils/__init__.py 2024-08-09 07:45:39 UTC (rev 9876)
+++ trunk/docutils/docutils/utils/__init__.py 2024-08-09 07:52:36 UTC (rev 9877)
@@ -20,7 +20,7 @@
from pathlib import PurePath, Path
from typing import TYPE_CHECKING
-from docutils import ApplicationError, DataError, __version_info__
+from docutils import ApplicationError, DataError
from docutils import io, nodes
# for backwards compatibility
from docutils.nodes import unescape # noqa: F401
@@ -31,7 +31,6 @@
from typing_extensions import TypeAlias
- from docutils import VersionInfo
from docutils.nodes import Element, Text
from docutils.frontend import Values
@@ -874,46 +873,3 @@
except AttributeError:
output_file = None
return '%s(%r, %s)' % (self.__class__.__name__, output_file, self.list)
-
-
-release_level_abbreviations: dict[str, str] = {
- 'alpha': 'a',
- 'beta': 'b',
- 'candidate': 'rc',
- 'final': '',
-}
-
-
-def version_identifier(version_info: VersionInfo | None = None) -> str:
- """
- Return a version identifier string built from `version_info`, a
- `docutils.VersionInfo` namedtuple instance or compatible tuple. If
- `version_info` is not provided, by default return a version identifier
- string based on `docutils.__version_info__` (i.e. the current Docutils
- version).
- """
- if version_info is None:
- version_info = __version_info__
- if version_info.micro:
- micro = '.%s' % version_info.micro
- else:
- # 0 is omitted:
- micro = ''
- releaselevel = release_level_abbreviations[version_info.releaselevel]
- if version_info.serial:
- serial = version_info.serial
- else:
- # 0 is omitted:
- serial = ''
- if version_info.release:
- dev = ''
- else:
- dev = '.dev'
- version = '%s.%s%s%s%s%s' % (
- version_info.major,
- version_info.minor,
- micro,
- releaselevel,
- serial,
- dev)
- return version
Modified: trunk/docutils/test/test__init__.py
===================================================================
--- trunk/docutils/test/test__init__.py 2024-08-09 07:45:39 UTC (rev 9876)
+++ trunk/docutils/test/test__init__.py 2024-08-09 07:52:36 UTC (rev 9877)
@@ -8,6 +8,8 @@
Test module for the docutils' __init__.py.
"""
+from __future__ import annotations
+
from pathlib import Path
import sys
import unittest
@@ -22,6 +24,42 @@
from docutils import VersionInfo
+_RELEASE_LEVEL_ABBREVIATIONS: dict[str, str] = {
+ 'alpha': 'a',
+ 'beta': 'b',
+ 'candidate': 'rc',
+ 'final': '',
+}
+
+
+def version_identifier(version_info: VersionInfo) -> str:
+ """
+ Return a version identifier string built from `version_info`, a
+ `docutils.VersionInfo` namedtuple instance or compatible tuple. If
+ `version_info` is not provided, by default return a version identifier
+ string based on `docutils.__version_info__` (i.e. the current Docutils
+ version).
+ """
+ if version_info.micro:
+ micro = f'.{version_info.micro}'
+ else:
+ # 0 is omitted:
+ micro = ''
+ releaselevel = _RELEASE_LEVEL_ABBREVIATIONS[version_info.releaselevel]
+ if version_info.serial:
+ serial = version_info.serial
+ else:
+ # 0 is omitted:
+ serial = ''
+ if version_info.release:
+ dev = ''
+ else:
+ dev = '.dev'
+ version = (f'{version_info.major}.{version_info.minor}{micro}'
+ f'{releaselevel}{serial}{dev}')
+ return version
+
+
class ApplicationErrorTests(unittest.TestCase):
def test_message(self):
@@ -73,7 +111,7 @@
def test__version__(self):
"""Test that __version__ is equivalent to __version_info__."""
self.assertEqual(
- docutils.utils.version_identifier(docutils.__version_info__),
+ version_identifier(docutils.__version_info__),
docutils.__version__, f'{docutils.__version_info__} differs')
def test_version_info_comparing(self):
@@ -104,8 +142,7 @@
VersionInfo(0, 2, 0, 'final', 0, True),
]
# transform to version strings
- versions = [docutils.utils.version_identifier(vinfo)
- for vinfo in versioninfos]
+ versions = [version_identifier(vinfo) for vinfo in versioninfos]
# ensure version infos corresponding to the dev cycle are ascending
self.assertEqual(versions, devcycle.split())
Modified: trunk/docutils/test/test_utils/test__init__.py
===================================================================
--- trunk/docutils/test/test_utils/test__init__.py 2024-08-09 07:45:39 UTC (rev 9876)
+++ trunk/docutils/test/test_utils/test__init__.py 2024-08-09 07:52:36 UTC (rev 9877)
@@ -19,9 +19,7 @@
# so we import the local `docutils` package.
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
-import docutils
from docutils import nodes, utils
-import docutils.utils.math
TEST_ROOT = Path(__file__).parents[1] # ./test/ from the docutils root
@@ -239,29 +237,6 @@
class HelperFunctionTests(unittest.TestCase):
-
- # Test conversion from `version information tuple` to a PEP 440 compliant
- # Docutils version identifier.
- # See 'Version Numbering' in docs/dev/policies.txt.
- def test_version_identifier(self):
- release_0_14_final = docutils.VersionInfo(
- major=0, minor=14, micro=0,
- releaselevel='final', serial=0, release=True)
- self.assertEqual(utils.version_identifier(release_0_14_final), '0.14')
- dev_0_15_beta = docutils.VersionInfo(
- major=0, minor=15, micro=0,
- releaselevel='beta', serial=0, release=False)
- self.assertEqual(utils.version_identifier(dev_0_15_beta), '0.15b.dev')
- release_0_14_rc1 = docutils.VersionInfo(
- major=0, minor=14, micro=0,
- releaselevel='candidate', serial=1, release=True)
- self.assertEqual(utils.version_identifier(release_0_14_rc1), '0.14rc1')
-
- def test_implicit_version_identifier(self):
- self.assertEqual(
- utils.version_identifier(docutils.__version_info__),
- utils.version_identifier())
-
def test_normalize_language_tag(self):
self.assertEqual(utils.normalize_language_tag('de'), ['de'])
self.assertEqual(utils.normalize_language_tag('de-AT'),
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <mi...@us...> - 2024-08-10 08:12:17
|
Revision: 9881
http://sourceforge.net/p/docutils/code/9881
Author: milde
Date: 2024-08-10 08:12:14 +0000 (Sat, 10 Aug 2024)
Log Message:
-----------
Smaller fixups (formatting, comments)
Modified Paths:
--------------
trunk/docutils/docutils/io.py
trunk/docutils/docutils/languages/__init__.py
trunk/docutils/docutils/nodes.py
trunk/docutils/docutils/parsers/rst/directives/admonitions.py
trunk/docutils/docutils/parsers/rst/languages/__init__.py
trunk/docutils/docutils/parsers/rst/states.py
trunk/docutils/docutils/readers/__init__.py
trunk/docutils/docutils/statemachine.py
trunk/docutils/docutils/transforms/frontmatter.py
trunk/docutils/docutils/transforms/references.py
trunk/docutils/docutils/utils/__init__.py
trunk/docutils/docutils/utils/math/tex2mathml_extern.py
trunk/docutils/docutils/utils/smartquotes.py
trunk/docutils/docutils/writers/html4css1/__init__.py
trunk/docutils/docutils/writers/manpage.py
trunk/docutils/test/alltests.py
trunk/docutils/test/test_io.py
Modified: trunk/docutils/docutils/io.py
===================================================================
--- trunk/docutils/docutils/io.py 2024-08-09 13:37:52 UTC (rev 9880)
+++ trunk/docutils/docutils/io.py 2024-08-10 08:12:14 UTC (rev 9881)
@@ -39,7 +39,7 @@
_locale_encoding: str | None = (locale.getlocale()[1]
or locale.getdefaultlocale()[1]
).lower()
-except: # NoQA: E722
+except: # NoQA: E722 (catchall)
# Any problem determining the locale: use None
_locale_encoding = None
try:
Modified: trunk/docutils/docutils/languages/__init__.py
===================================================================
--- trunk/docutils/docutils/languages/__init__.py 2024-08-09 13:37:52 UTC (rev 9880)
+++ trunk/docutils/docutils/languages/__init__.py 2024-08-10 08:12:14 UTC (rev 9881)
@@ -52,9 +52,8 @@
def __init__(self) -> None:
self.cache: dict[str, LanguageModuleT] = {}
- def import_from_packages(
- self, name: str, reporter: Reporter = None
- ) -> LanguageModuleT:
+ def import_from_packages(self, name: str, reporter: Reporter = None
+ ) -> LanguageModuleT:
"""Try loading module `name` from `self.packages`."""
module = None
for package in self.packages:
@@ -88,9 +87,8 @@
):
raise ImportError
- def __call__(
- self, language_code: str, reporter: Reporter = None
- ) -> LanguageModuleT:
+ def __call__(self, language_code: str, reporter: Reporter = None
+ ) -> LanguageModuleT:
try:
return self.cache[language_code]
except KeyError:
Modified: trunk/docutils/docutils/nodes.py
===================================================================
--- trunk/docutils/docutils/nodes.py 2024-08-09 13:37:52 UTC (rev 9880)
+++ trunk/docutils/docutils/nodes.py 2024-08-10 08:12:14 UTC (rev 9881)
@@ -2483,7 +2483,7 @@
children = (p,) + children
try:
Element.__init__(self, rawsource, *children, **attributes)
- except: # NoQA: E722
+ except: # NoQA: E722 (catchall)
print('system_message: children=%r' % (children,))
raise
Modified: trunk/docutils/docutils/parsers/rst/directives/admonitions.py
===================================================================
--- trunk/docutils/docutils/parsers/rst/directives/admonitions.py 2024-08-09 13:37:52 UTC (rev 9880)
+++ trunk/docutils/docutils/parsers/rst/directives/admonitions.py 2024-08-10 08:12:14 UTC (rev 9881)
@@ -96,6 +96,6 @@
node_class = nodes.tip
-class Warning(BaseAdmonition): # NoQA: A001 (builtin name)
+class Warning(BaseAdmonition): # NoQA: A001 (builtin shadowing)
node_class = nodes.warning
Modified: trunk/docutils/docutils/parsers/rst/languages/__init__.py
===================================================================
--- trunk/docutils/docutils/parsers/rst/languages/__init__.py 2024-08-09 13:37:52 UTC (rev 9880)
+++ trunk/docutils/docutils/parsers/rst/languages/__init__.py 2024-08-10 08:12:14 UTC (rev 9881)
@@ -51,14 +51,11 @@
def check_content(self, module: types.ModuleType) -> NoReturn:
...
- def check_content(
- self, module: RSTLanguageModule | types.ModuleType
- ) -> None:
+ def check_content(self, module: RSTLanguageModule | types.ModuleType
+ ) -> None:
"""Check if we got an rST language module."""
- if not (
- isinstance(module.directives, dict)
- and isinstance(module.roles, dict)
- ):
+ if not (isinstance(module.directives, dict)
+ and isinstance(module.roles, dict)):
raise ImportError
Modified: trunk/docutils/docutils/parsers/rst/states.py
===================================================================
--- trunk/docutils/docutils/parsers/rst/states.py 2024-08-09 13:37:52 UTC (rev 9880)
+++ trunk/docutils/docutils/parsers/rst/states.py 2024-08-10 08:12:14 UTC (rev 9881)
@@ -2889,10 +2889,8 @@
text = parts[0].rstrip()
textnode = nodes.Text(text)
node_list[-1] += textnode
- node_list += [
- nodes.classifier(unescape(part, True), part)
- for part in parts[1:]
- ]
+ node_list += [nodes.classifier(unescape(part, True), part)
+ for part in parts[1:]]
else:
node_list[-1] += node
return node_list, messages
Modified: trunk/docutils/docutils/readers/__init__.py
===================================================================
--- trunk/docutils/docutils/readers/__init__.py 2024-08-09 13:37:52 UTC (rev 9880)
+++ trunk/docutils/docutils/readers/__init__.py 2024-08-10 08:12:14 UTC (rev 9881)
@@ -124,9 +124,8 @@
@overload
-def get_reader_class(
- reader_name: Literal['standalone']
-) -> type[standalone.Reader]:
+def get_reader_class(reader_name: Literal['standalone']
+ ) -> type[standalone.Reader]:
...
Modified: trunk/docutils/docutils/statemachine.py
===================================================================
--- trunk/docutils/docutils/statemachine.py 2024-08-09 13:37:52 UTC (rev 9880)
+++ trunk/docutils/docutils/statemachine.py 2024-08-10 08:12:14 UTC (rev 9881)
@@ -264,7 +264,7 @@
else:
transitions = None
state = self.get_state(next_state)
- except: # NoQA: E722
+ except: # NoQA: E722 (catchall)
if self.debug:
self.error()
raise
@@ -673,7 +673,7 @@
try:
del self.transitions[name]
self.transition_order.remove(name)
- except: # NoQA: E722
+ except: # NoQA: E722 (catchall)
raise UnknownTransitionError(name)
def make_transition(self, name, next_state=None):
Modified: trunk/docutils/docutils/transforms/frontmatter.py
===================================================================
--- trunk/docutils/docutils/transforms/frontmatter.py 2024-08-09 13:37:52 UTC (rev 9880)
+++ trunk/docutils/docutils/transforms/frontmatter.py 2024-08-10 08:12:14 UTC (rev 9881)
@@ -416,7 +416,7 @@
field['classes'].append(classvalue)
docinfo.append(field)
nodelist = []
- if len(docinfo) != 0:
+ if len(docinfo):
nodelist.append(docinfo)
if topics['dedication']:
nodelist.append(topics['dedication'])
Modified: trunk/docutils/docutils/transforms/references.py
===================================================================
--- trunk/docutils/docutils/transforms/references.py 2024-08-09 13:37:52 UTC (rev 9880)
+++ trunk/docutils/docutils/transforms/references.py 2024-08-10 08:12:14 UTC (rev 9881)
@@ -114,14 +114,11 @@
def apply(self) -> None:
anonymous_refs = [
- node for node
- in self.document.findall(nodes.reference)
+ node for node in self.document.findall(nodes.reference)
if node.get('anonymous')]
anonymous_targets = [
- node for node
- in self.document.findall(nodes.target)
- if node.get('anonymous')
- ]
+ node for node in self.document.findall(nodes.target)
+ if node.get('anonymous')]
if len(anonymous_refs) != len(anonymous_targets):
msg = self.document.reporter.error(
'Anonymous hyperlink mismatch: %s references but %s '
Modified: trunk/docutils/docutils/utils/__init__.py
===================================================================
--- trunk/docutils/docutils/utils/__init__.py 2024-08-09 13:37:52 UTC (rev 9880)
+++ trunk/docutils/docutils/utils/__init__.py 2024-08-10 08:12:14 UTC (rev 9881)
@@ -682,11 +682,9 @@
if found == -1:
parts.append(text[start:])
return ''.join(parts)
- parts.extend((
- text[start:found],
- '\x00' + text[found + 1:found + 2],
- ))
- start = found + 2 # skip character after escape
+ parts.extend((text[start:found],
+ '\x00' + text[found + 1:found + 2]))
+ start = found + 2 # skip character after escape
def split_escaped_whitespace(text: str) -> list[str]:
@@ -781,11 +779,10 @@
subtags = list(tag.split('_'))
base_tag = (subtags.pop(0),)
# find all combinations of subtags
- taglist = [
- '-'.join(base_tag + tags)
- for n in range(len(subtags), 0, -1)
- for tags in itertools.combinations(subtags, n)
- ]
+ taglist = ['-'.join(base_tag + tags)
+ for n in range(len(subtags), 0, -1)
+ for tags in itertools.combinations(subtags, n)
+ ]
taglist += base_tag
return taglist
Modified: trunk/docutils/docutils/utils/math/tex2mathml_extern.py
===================================================================
--- trunk/docutils/docutils/utils/math/tex2mathml_extern.py 2024-08-09 13:37:52 UTC (rev 9880)
+++ trunk/docutils/docutils/utils/math/tex2mathml_extern.py 2024-08-10 08:12:14 UTC (rev 9881)
@@ -171,12 +171,11 @@
details = []
if result.stderr:
lines = result.stderr.splitlines()
- details.extend((
- nodes.paragraph('', lines[0]),
- nodes.literal_block('', '\n'.join(lines[1:3])),
- nodes.paragraph('', '\n'.join(lines[3:]),
- classes=['pre-wrap']),
- ))
+ details += [nodes.paragraph('', lines[0]),
+ nodes.literal_block('', '\n'.join(lines[1:3])),
+ nodes.paragraph('', '\n'.join(lines[3:]),
+ classes=['pre-wrap']),
+ ]
_check_result(result, details=details)
return result.stdout
Modified: trunk/docutils/docutils/utils/smartquotes.py
===================================================================
--- trunk/docutils/docutils/utils/smartquotes.py 2024-08-09 13:37:52 UTC (rev 9880)
+++ trunk/docutils/docutils/utils/smartquotes.py 2024-08-10 08:12:14 UTC (rev 9881)
@@ -911,7 +911,7 @@
try:
locale.setlocale(locale.LC_ALL, '') # set to user defaults
defaultlanguage = locale.getlocale()[0]
- except: # NoQA: E722
+ except: # NoQA: E722 (catchall)
defaultlanguage = 'en'
# Normalize and drop unsupported subtags:
Modified: trunk/docutils/docutils/writers/html4css1/__init__.py
===================================================================
--- trunk/docutils/docutils/writers/html4css1/__init__.py 2024-08-09 13:37:52 UTC (rev 9880)
+++ trunk/docutils/docutils/writers/html4css1/__init__.py 2024-08-10 08:12:14 UTC (rev 9881)
@@ -932,10 +932,8 @@
"""
def visit_list_item(self, node):
- children = [
- child for child in node.children
- if not isinstance(child, nodes.Invisible)
- ]
+ children = [child for child in node.children
+ if not isinstance(child, nodes.Invisible)]
if (children and isinstance(children[0], nodes.paragraph)
and (isinstance(children[-1], nodes.bullet_list)
or isinstance(children[-1], nodes.enumerated_list))):
Modified: trunk/docutils/docutils/writers/manpage.py
===================================================================
--- trunk/docutils/docutils/writers/manpage.py 2024-08-09 13:37:52 UTC (rev 9880)
+++ trunk/docutils/docutils/writers/manpage.py 2024-08-10 08:12:14 UTC (rev 9881)
@@ -171,11 +171,10 @@
del cell_lines[-1]
def as_list(self):
- text = [
- '.TS\n',
- ' '.join(self._options) + ';\n',
- '%s.\n' % '|'.join(self._coldefs),
- ]
+ text = ['.TS\n',
+ ' '.join(self._options) + ';\n',
+ '%s.\n' % '|'.join(self._coldefs),
+ ]
for row in self._rows:
# row = array of cells. cell = array of lines.
text.append('T{\n')
Modified: trunk/docutils/test/alltests.py
===================================================================
--- trunk/docutils/test/alltests.py 2024-08-09 13:37:52 UTC (rev 9880)
+++ trunk/docutils/test/alltests.py 2024-08-10 08:12:14 UTC (rev 9881)
@@ -12,7 +12,7 @@
All modules named 'test_*.py' in the current directory, and recursively in
subdirectories (packages) called 'test_*', are loaded and test suites within
are run.
-""" # NoQA: A001
+""" # NoQA: A001 (shadowing builtin `__doc__`)
import atexit
import platform
Modified: trunk/docutils/test/test_io.py
===================================================================
--- trunk/docutils/test/test_io.py 2024-08-09 13:37:52 UTC (rev 9880)
+++ trunk/docutils/test/test_io.py 2024-08-10 08:12:14 UTC (rev 9881)
@@ -31,7 +31,7 @@
SUPPRESS_ENCODING_WARNING = sys.flags.warn_default_encoding
else:
SUPPRESS_ENCODING_WARNING = False
- EncodingWarning = UnicodeWarning # NoQA: A001 (builtin name)
+ EncodingWarning = UnicodeWarning # NoQA: A001 (builtin in Py > 0.9)
# DATA_ROOT is ./test/data/ from the docutils root
DATA_ROOT = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'data')
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|