SF.net SVN: docutils:[9945 ] trunk/docutils/docutils

milde--- via Docutils-checkins <[email protected]>
Newsgroups gmane.text.docutils.cvs
Message-ID <[email protected]>
Revision: 9945
          http://sourceforge.net/p/docutils/code/9945
Author:   milde
Date:     2024-10-04 12:21:52 +0000 (Fri, 04 Oct 2024)
Log Message:
-----------
Use custom TypeAlias `StrPath` for `str`-based file system path vars.

Define TypeAlias for "str or os.PathLike" in docutils.nodes
(as this module does not depend on other docutils modules).
Import and use in all places where ``str | os.PathLike`` is expected.

Align formatting, use f-strings where it helps clarity.

Modified Paths:
--------------
    trunk/docutils/docutils/core.py
    trunk/docutils/docutils/examples.py
    trunk/docutils/docutils/frontend.py
    trunk/docutils/docutils/io.py
    trunk/docutils/docutils/nodes.py
    trunk/docutils/docutils/parsers/rst/directives/misc.py
    trunk/docutils/docutils/utils/__init__.py

Modified: trunk/docutils/docutils/core.py
===================================================================
--- trunk/docutils/docutils/core.py	2024-10-02 08:40:47 UTC (rev 9944)
+++ trunk/docutils/docutils/core.py	2024-10-04 12:21:52 UTC (rev 9945)
@@ -22,6 +22,7 @@
 import os
 import sys
 import warnings
+from typing import TYPE_CHECKING
 
 from docutils import (__version__, __version_details__, SettingsSpec,
                       io, utils, readers, parsers, writers)
@@ -28,7 +29,10 @@
 from docutils.frontend import OptionParser
 from docutils.readers import doctree
 
+if TYPE_CHECKING:
+    from docutils.nodes import StrPath
 
+
 class Publisher:
 
     """
@@ -196,7 +200,7 @@
 
     def set_source(self,
                    source: str | None = None,
-                   source_path: str | os.PathLike[str] | None = None,
+                   source_path: StrPath | None = None,
                    ) -> None:
         if source_path is None:
             source_path = self.settings._source
@@ -210,7 +214,7 @@
 
     def set_destination(self,
                         destination: str | None = None,
-                        destination_path: str | os.PathLike[str] | None = None,
+                        destination_path: StrPath | None = None,
                         ) -> None:
         if destination_path is None:
             if (self.settings.output and self.settings._destination

Modified: trunk/docutils/docutils/examples.py
===================================================================
--- trunk/docutils/docutils/examples.py	2024-10-02 08:40:47 UTC (rev 9944)
+++ trunk/docutils/docutils/examples.py	2024-10-04 12:21:52 UTC (rev 9945)
@@ -18,16 +18,16 @@
 from docutils import core, io
 
 if TYPE_CHECKING:
-    import os
     from typing import Any, Literal
 
     from docutils import nodes
+    from docutils.nodes import StrPath
     from docutils.core import Publisher
 
 
 def html_parts(input_string: str | bytes,
-               source_path: str | os.PathLike[str] | None = None,
-               destination_path: str | os.PathLike[str] | None = None,
+               source_path: StrPath | None = None,
+               destination_path: StrPath | None = None,
                input_encoding: Literal['unicode'] | str = 'unicode',
                doctitle: bool = True,
                initial_header_level: int = 1,
@@ -66,8 +66,8 @@
 
 
 def html_body(input_string: str | bytes,
-              source_path: str | os.PathLike[str] | None = None,
-              destination_path: str | os.PathLike[str] | None = None,
+              source_path: StrPath | None = None,
+              destination_path: StrPath | None = None,
               input_encoding: Literal['unicode'] | str = 'unicode',
               output_encoding: Literal['unicode'] | str = 'unicode',
               doctitle: bool = True,
@@ -95,7 +95,7 @@
 
 
 def internals(source: str,
-              source_path: str | os.PathLike[str] | None = None,
+              source_path: StrPath | None = None,
               input_encoding: Literal['unicode'] | str = 'unicode',
               settings_overrides: dict[str, Any] | None = None,
               ) -> tuple[nodes.document, Publisher]:

Modified: trunk/docutils/docutils/frontend.py
===================================================================
--- trunk/docutils/docutils/frontend.py	2024-10-02 08:40:47 UTC (rev 9944)
+++ trunk/docutils/docutils/frontend.py	2024-10-04 12:21:52 UTC (rev 9945)
@@ -74,9 +74,8 @@
     from typing import Any, ClassVar, Literal, Protocol
 
     from docutils import SettingsSpec, _OptionTuple, _SettingsSpecTuple
+    from docutils.io import StrPath
 
-    _FsPath = str | os.PathLike[str]
-
     class _OptionValidator(Protocol):
         def __call__(
             self,
@@ -479,9 +478,9 @@
     return lc_quotes
 
 
-def make_paths_absolute(pathdict: dict[str, list[_FsPath] | _FsPath],
+def make_paths_absolute(pathdict: dict[str, list[StrPath] | StrPath],
                         keys: tuple[str],
-                        base_path: _FsPath | None = None,
+                        base_path: StrPath | None = None,
                         ) -> None:
     """
     Interpret filesystem path settings relative to the `base_path` given.
@@ -505,7 +504,7 @@
             pathdict[key] = value
 
 
-def make_one_path_absolute(base_path: _FsPath, path: _FsPath) -> str:
+def make_one_path_absolute(base_path: StrPath, path: StrPath) -> str:
     # deprecated, will be removed
     warnings.warn('frontend.make_one_path_absolute() will be removed '
                   'in Docutils 0.23.', DeprecationWarning, stacklevel=2)
@@ -954,7 +953,7 @@
                 self.defaults.update(component.settings_default_overrides)
 
     @classmethod
-    def get_standard_config_files(cls) -> Sequence[_FsPath]:
+    def get_standard_config_files(cls) -> Sequence[StrPath]:
         """Return list of config files, from environment or standard."""
         if 'DOCUTILSCONFIG' in os.environ:
             config_files = os.environ['DOCUTILSCONFIG'].split(os.pathsep)
@@ -1001,7 +1000,8 @@
         values._config_files = self.config_files
         return values
 
-    def check_args(self, args: list[str]) -> tuple[str | None, str | None]:
+    def check_args(self, args: list[str]) -> tuple[str|None, str|None]:
+        # provisional: argument handling will change, see RELEASE_NOTES
         source = destination = None
         if args:
             source = args.pop(0)

Modified: trunk/docutils/docutils/io.py
===================================================================
--- trunk/docutils/docutils/io.py	2024-10-02 08:40:47 UTC (rev 9944)
+++ trunk/docutils/docutils/io.py	2024-10-04 12:21:52 UTC (rev 9945)
@@ -25,6 +25,7 @@
     from typing import Any, BinaryIO, ClassVar, Final, Literal, TextIO
 
     from docutils import nodes
+    from docutils.nodes import StrPath
 
 # Guess the locale's preferred encoding.
 # If no valid guess can be made, _locale_encoding is set to `None`:
@@ -93,7 +94,7 @@
     def __init__(
         self,
         source: str | TextIO | nodes.document | None = None,
-        source_path: str | os.PathLike[str] | None = None,
+        source_path: StrPath | None = None,
         encoding: str | Literal['unicode'] | None = 'utf-8',
         error_handler: str | None = 'strict',
     ) -> None:
@@ -239,7 +240,7 @@
     def __init__(
         self,
         destination: TextIO | str | bytes | None = None,
-        destination_path: str | os.PathLike[str] | None = None,
+        destination_path: StrPath | None = None,
         encoding: str | None = None,
         error_handler: str | None = 'strict',
     ) -> None:
@@ -252,7 +253,7 @@
         self.destination: TextIO | str | bytes | None = destination
         """The destination for output data."""
 
-        self.destination_path: str | os.PathLike[str] | None = destination_path
+        self.destination_path: StrPath | None = destination_path
         """A text reference to the destination."""
 
         if not destination_path:
@@ -396,7 +397,7 @@
     def __init__(
         self,
         source: TextIO | None = None,
-        source_path: str | os.PathLike[str] | None = None,
+        source_path: StrPath | None = None,
         encoding: str | Literal['unicode'] | None = 'utf-8',
         error_handler: str | None = 'strict',
         autoclose: bool = True,
@@ -481,16 +482,15 @@
     # (Do not use binary mode ('wb') for text files, as this prevents the
     # conversion of newlines to the system specific default.)
 
-    def __init__(
-        self,
-        destination: TextIO | None = None,
-        destination_path: str | os.PathLike[str] | None = None,
-        encoding: str | None = None,
-        error_handler: str | None = 'strict',
-        autoclose: bool = True,
-        handle_io_errors: None = None,
-        mode=None,
-    ) -> None:
+    def __init__(self,
+                 destination: TextIO | None = None,
+                 destination_path: StrPath | None = None,
+                 encoding: str | None = None,
+                 error_handler: str | None = 'strict',
+                 autoclose: bool = True,
+                 handle_io_errors: None = None,
+                 mode=None,
+                 ) -> None:
         """
         :Parameters:
             - `destination`: either a file-like object (which is written
@@ -508,8 +508,7 @@
               support for text files.
         """
         super().__init__(
-            destination, destination_path, encoding, error_handler,
-        )
+            destination, destination_path, encoding, error_handler)
         self.opened = True
         self.autoclose = autoclose
         if handle_io_errors is not None:

Modified: trunk/docutils/docutils/nodes.py
===================================================================
--- trunk/docutils/docutils/nodes.py	2024-10-02 08:40:47 UTC (rev 9944)
+++ trunk/docutils/docutils/nodes.py	2024-10-04 12:21:52 UTC (rev 9945)
@@ -34,7 +34,7 @@
 # import xml.dom.minidom as dom # -> conditional import in Node.asdom()
 #                                    and document.asdom()
 
-# import docutils.transforms # -> conditional import in document.__init__()
+# import docutils.transforms # -> delayed import in document.__init__()
 
 if TYPE_CHECKING:
     import numbers
@@ -62,6 +62,9 @@
                                          _ContentModelQuantifier]
     _ContentModelTuple: TypeAlias = tuple[_ContentModelItem, ...]
 
+    StrPath: TypeAlias = str | os.PathLike[str]
+    """File system path. No bytes!"""
+
     _UpdateFun: TypeAlias = Callable[[str, Any, bool], None]
 
 
@@ -81,7 +84,7 @@
     Override in subclass instances that are not terminal nodes.
     """
 
-    source: str | os.PathLike[str] | None = None
+    source: StrPath | None = None
     """Path or description of the input source which generated this Node."""
 
     line: int | None = None
@@ -1750,7 +1753,7 @@
                  ) -> None:
         Element.__init__(self, *args, **kwargs)
 
-        self.current_source: str | os.PathLike[str] | None = None
+        self.current_source: StrPath | None = None
         """Path to or description of the input source being processed."""
 
         self.current_line: int | None = None
@@ -1831,7 +1834,7 @@
         self.transformer: Transformer = docutils.transforms.Transformer(self)
         """Storage for transforms to be applied to this document."""
 
-        self.include_log: list[tuple[str|os.PathLike[str], tuple]] = []
+        self.include_log: list[tuple[StrPath, tuple]] = []
         """The current source's parents (to detect inclusion loops)."""
 
         self.decoration: decoration | None = None
@@ -1876,8 +1879,7 @@
         base_id = ''
         id = ''
         for name in node['names']:
-            if id_prefix:
-                # allow names starting with numbers if `id_prefix`
+            if id_prefix:  # allow names starting with numbers
                 base_id = make_id('x'+name)[1:]
             else:
                 base_id = make_id(name)
@@ -1893,12 +1895,11 @@
             else:
                 prefix = id_prefix + auto_id_prefix
                 if prefix.endswith('%'):
-                    prefix = '%s%s-' % (prefix[:-1],
-                                        suggested_prefix
-                                        or make_id(node.tagname))
+                    prefix = f"""{prefix[:-1]}{suggested_prefix
+                                               or make_id(node.tagname)}-"""
             while True:
                 self.id_counter[prefix] += 1
-                id = '%s%d' % (prefix, self.id_counter[prefix])
+                id = f'{prefix}{self.id_counter[prefix]}'
                 if id not in self.ids:
                     break
         node['ids'].append(id)
@@ -2096,7 +2097,7 @@
         self.transform_messages.append(message)
 
     def note_source(self,
-                    source: str | os.PathLike[str] | None,
+                    source: StrPath | None,
                     offset: int | None,
                     ) -> None:
         self.current_source = source and os.fspath(source)

Modified: trunk/docutils/docutils/parsers/rst/directives/misc.py
===================================================================
--- trunk/docutils/docutils/parsers/rst/directives/misc.py	2024-10-02 08:40:47 UTC (rev 9944)
+++ trunk/docutils/docutils/parsers/rst/directives/misc.py	2024-10-04 12:21:52 UTC (rev 9945)
@@ -9,7 +9,6 @@
 __docformat__ = 'reStructuredText'
 
 import re
-import sys
 import time
 from pathlib import Path
 from typing import TYPE_CHECKING
@@ -23,18 +22,9 @@
 from docutils.transforms import misc
 
 if TYPE_CHECKING:
-    import os
-    if sys.version_info[:2] >= (3, 12):
-        from typing import TypeAlias
-    else:
-        from typing_extensions import TypeAlias
+    from docutils.nodes import Node, StrPath
 
-    from docutils.nodes import Node
 
-    StrPath: TypeAlias = str | os.PathLike[str]
-    """File system path. No bytes!"""
-
-
 def adapt_path(path: str, source='', root_prefix='/') -> str:
     # Adapt path to files to include or embed.
     # `root_prefix` is prepended to absolute paths (cf. root_prefix setting),

Modified: trunk/docutils/docutils/utils/__init__.py
===================================================================
--- trunk/docutils/docutils/utils/__init__.py	2024-10-02 08:40:47 UTC (rev 9944)
+++ trunk/docutils/docutils/utils/__init__.py	2024-10-04 12:21:52 UTC (rev 9945)
@@ -33,10 +33,9 @@
     else:
         from typing_extensions import TypeAlias
 
-    from docutils.nodes import Node
+    from docutils.nodes import Node, StrPath
     from docutils.frontend import Values
 
-    StrPath: TypeAlias = str | os.PathLike[str]
     _ObserverFunc: TypeAlias = Callable[[nodes.system_message], None]
 
 

This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.