diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml new file mode 100644 index 0000000..06914b5 --- /dev/null +++ b/.github/workflows/publish.yml @@ -0,0 +1,41 @@ +name: Publish + +# Releases are published only from this workflow, and only for version tags +# (e.g. 1.2.0, 1.2.0rc1). The PyPI trusted publisher is bound to this file +# name and to the "pypi" environment: do not rename it. +on: + push: + tags: [ '[0-9]+.[0-9]+.[0-9]+*' ] + +permissions: {} + +jobs: + # Lint, tests, the tag/__version__ check and the build, from test.yml. + ci: + # A job-level call resolves from this commit, not the runner's files, so + # the newer "$/" self-repository syntax buys nothing here. + uses: ./.github/workflows/test.yml # zizmor: ignore[self-repository] + permissions: + contents: read + + publish: + name: Publish to PyPI + # Must stay a job of this workflow: PyPI trusted publishing does not + # accept uploads from inside a reusable (called) workflow. + needs: ci + runs-on: ubuntu-latest + environment: + name: pypi + url: https://pypi.org/project/ipython-pygments-lexers/ + permissions: + id-token: write # OIDC for uploading to PyPI + + steps: + - name: Download packages + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: dist + path: dist/ + + - name: Publish package distributions to PyPI + uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3 diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 565ac95..59b9f63 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -3,10 +3,11 @@ name: Tests on: push: branches: [ main ] - tags: [ '*' ] pull_request: branches: [ main ] workflow_dispatch: + # Called by publish.yml so a release runs the same checks and build. + workflow_call: permissions: contents: read @@ -44,11 +45,18 @@ jobs: run: python3 -m mypy tests: + name: tests (Python ${{ matrix.python-version }}${{ matrix.pygments && format(', pygments{0}', matrix.pygments) || '' }}) runs-on: ubuntu-latest strategy: fail-fast: false matrix: python-version: ["3.11", "3.12", "3.13", "3.14", "3.15"] + pygments: [""] # latest + include: + # Oldest supported Pygments, to keep the lower bound honest. This is + # a separate job because it differs from the [""] axis value. + - python-version: "3.11" + pygments: "==2.14.0" steps: - name: Checkout @@ -62,21 +70,18 @@ jobs: python-version: ${{ matrix.python-version }} - name: Install dependencies + env: + PYGMENTS_SPEC: ${{ matrix.pygments }} run: | python3 -m pip install --upgrade pip - python3 -m pip install . --group test + python3 -m pip install . --group test "pygments${PYGMENTS_SPEC}" - name: Test with pytest run: | python3 -m pytest -v - publish: + build: runs-on: ubuntu-latest - if: ${{ startsWith(github.ref, 'refs/tags/') }} - needs: [lint, tests] - permissions: - id-token: write # OIDC for uploading to PyPI - steps: - name: Checkout uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -86,12 +91,32 @@ jobs: - name: Set up Python uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: - python-version: "3.11" + python-version: "3.x" + + - name: Check tag matches __version__ + if: ${{ startsWith(github.ref, 'refs/tags/') }} + run: | + version=$(python3 -c 'import re, pathlib; print(re.search(r"^__version__ = \"(.+)\"", pathlib.Path("ipython_pygments_lexers/__init__.py").read_text(), re.M).group(1))') + if [ "${GITHUB_REF_NAME}" != "${version}" ]; then + echo "::error::Tag ${GITHUB_REF_NAME} does not match __version__ ${version}" + exit 1 + fi - name: Build packages run: | + python3 -m pip install --upgrade pip python3 -m pip install build python3 -m build - - name: Publish package distributions to PyPI - uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3 + - name: Test the built wheel + run: | + python3 -m pip install dist/*.whl --group test + cd "${RUNNER_TEMP}" + python3 -m pytest --import-mode=importlib "${GITHUB_WORKSPACE}/test_ipython_pygments_lexers.py" + + - name: Upload packages + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: dist + path: dist/ + if-no-files-found: error diff --git a/ipython_pygments_lexers.py b/ipython_pygments_lexers/__init__.py similarity index 77% rename from ipython_pygments_lexers.py rename to ipython_pygments_lexers/__init__.py index c17c9b0..37cbc47 100644 --- a/ipython_pygments_lexers.py +++ b/ipython_pygments_lexers/__init__.py @@ -7,8 +7,8 @@ Lexers for pure IPython (python + magic/shell commands) IPythonPartialTracebackLexer, IPythonTracebackLexer - Supports 2.x and 3.x via keyword `python3`. The partial traceback - lexer reads everything but the Python code appearing in a traceback. + The partial traceback lexer reads everything but the Python code + appearing in a traceback. The full lexer combines the partial lexer with an IPython lexer. IPythonConsoleLexer @@ -17,22 +17,26 @@ IPyLexer A friendly lexer which examines the first line of text and from it, decides whether to use an IPython lexer or an IPython console lexer. - This is probably the only lexer that needs to be explicitly added - to Pygments. + This lets one lexer handle both plain IPython code and console + sessions. """ # ----------------------------------------------------------------------------- -# Copyright (c) 2013, the IPython Development Team. +# Copyright (c) 2012-Present, IPython Development Team. # -# Distributed under the terms of the Modified BSD License. +# Distributed under the terms of the BSD 3-Clause License. # -# The full license is in the file COPYING.txt, distributed with this software. +# The full license is in the file LICENSE, distributed with this software. # ----------------------------------------------------------------------------- +from __future__ import annotations + __version__ = "1.1.1" # Standard library import re +from collections.abc import Iterator +from typing import TYPE_CHECKING, Any # Third party # do_insertions is missing from types-Pygments @@ -65,6 +69,16 @@ Text, ) +if TYPE_CHECKING: + from typing import Literal as TypingLiteral + from typing import TypeAlias + + from pygments.token import _TokenType + + #: An unprocessed token, as yielded by ``Lexer.get_tokens_unprocessed``. + UnprocessedToken: TypeAlias = tuple[int, _TokenType, str] + Mode: TypeAlias = TypingLiteral["input", "output", "tb"] + line_re = re.compile(".*?\n") __all__ = [ @@ -77,7 +91,7 @@ ] -ipython_tokens = [ +ipython_tokens: list[tuple[str, Any]] = [ ( r"(?s)(\s*)(%%capture)([^\n]*\n)(.*)", bygroups(Text, Operator, Text, using(Python3Lexer)), @@ -162,7 +176,9 @@ ] -class IPython3Lexer(Python3Lexer): +# types-Pygments does not include the individual lexer classes, so Python3Lexer +# is typed as Any. +class IPython3Lexer(Python3Lexer): # type: ignore[misc] """IPython code lexer (based on Python 3)""" name = "IPython" @@ -248,18 +264,17 @@ class IPythonTracebackLexer(DelegatingLexer): """ - # The lexer inherits from DelegatingLexer. The "root" lexer is an - # appropriate IPython lexer, which depends on the value of the boolean - # `python3`. First, we parse with the partial IPython traceback lexer. + # The lexer inherits from DelegatingLexer. The "root" lexer is + # IPython3Lexer. First, we parse with the partial IPython traceback lexer. # Then, any code marked with the "Other" token is delegated to the root # lexer. # name = "IPython Traceback" aliases = ["ipythontb", "ipython3tb"] - def __init__(self, **options): + def __init__(self, **options: Any) -> None: """ - A subclass of `DelegatingLexer` which delegates to the appropriate to either IPyLexer, + A subclass of `DelegatingLexer` which delegates to IPython3Lexer and IPythonPartialTracebackLexer. """ # note we need a __init__ doc, as otherwise it inherits the doc from the super class @@ -314,36 +329,41 @@ class IPythonConsoleLexer(Lexer): # Where '#' is the 'prompt number' or 'execution count' and 'D' # D is a number of dots matching the width of the execution count # - in1_regex = r"In \[[0-9]+\]: " - in2_regex = r" \.\.+\.: " - out_regex = r"Out\[[0-9]+\]: " + in1_regex: str = r"In \[[0-9]+\]: " + in2_regex: str = r" \.\.+\.: " + out_regex: str = r"Out\[[0-9]+\]: " #: The regex to determine when a traceback starts. ipytb_start = re.compile(r"^(\^C)?(-+\n)|^( File)(.*)(, line )(\d+\n)") - def __init__(self, **options): + mode: Mode + index: int + buffer: str + insertions: list[tuple[int, list[UnprocessedToken]]] + + def __init__(self, **options: Any) -> None: """Initialize the IPython console lexer. Parameters ---------- - in1_regex : RegexObject - The compiled regular expression used to detect the start - of inputs. Although the IPython configuration setting may have a - trailing whitespace, do not include it in the regex. If `None`, - then the default input prompt is assumed. - in2_regex : RegexObject - The compiled regular expression used to detect the continuation + in1_regex : str + The regular expression (as a string) used to detect the start of inputs. Although the IPython configuration setting may have a - trailing whitespace, do not include it in the regex. If `None`, - then the default input prompt is assumed. - out_regex : RegexObject - The compiled regular expression used to detect outputs. If `None`, - then the default output prompt is assumed. + trailing whitespace, do not include it in the regex. If not + given, the default input prompt is assumed. + in2_regex : str + The regular expression (as a string) used to detect the + continuation of inputs. Although the IPython configuration setting + may have a trailing whitespace, do not include it in the regex. + If not given, the default continuation prompt is assumed. + out_regex : str + The regular expression (as a string) used to detect outputs. + If not given, the default output prompt is assumed. """ - in1_regex = options.get("in1_regex", self.in1_regex) - in2_regex = options.get("in2_regex", self.in2_regex) - out_regex = options.get("out_regex", self.out_regex) + in1_regex: str = options.get("in1_regex", self.in1_regex) + in2_regex: str = options.get("in2_regex", self.in2_regex) + out_regex: str = options.get("out_regex", self.out_regex) # So that we can work with input and output prompts which have been # rstrip'd (possibly by editors) we also need rstrip'd variants. If @@ -358,16 +378,23 @@ def __init__(self, **options): out_regex_rstrip = out_regex.rstrip() + "\n" # Compile and save them all. - attrs = [ - "in1_regex", - "in2_regex", - "out_regex", - "in1_regex_rstrip", - "in2_regex_rstrip", - "out_regex_rstrip", - ] - for attr in attrs: - self.__setattr__(attr, re.compile(locals()[attr])) + self._in1_re = re.compile(in1_regex) + self._in2_re = re.compile(in2_regex) + self._out_re = re.compile(out_regex) + self._in1_rstrip_re = re.compile(in1_regex_rstrip) + self._in2_rstrip_re = re.compile(in2_regex_rstrip) + self._out_rstrip_re = re.compile(out_regex_rstrip) + # Backward compatibility: these instance attributes used to hold the + # compiled patterns, shadowing the class-level strings. + for attr, pattern in [ + ("in1_regex", self._in1_re), + ("in2_regex", self._in2_re), + ("out_regex", self._out_re), + ("in1_regex_rstrip", self._in1_rstrip_re), + ("in2_regex_rstrip", self._in2_rstrip_re), + ("out_regex_rstrip", self._out_rstrip_re), + ]: + setattr(self, attr, pattern) Lexer.__init__(self, **options) @@ -376,20 +403,21 @@ def __init__(self, **options): self.reset() - def reset(self): + def reset(self) -> None: self.mode = "output" self.index = 0 self.buffer = "" self.insertions = [] - def buffered_tokens(self): + def buffered_tokens(self) -> Iterator[UnprocessedToken]: """ Generator of unprocessed tokens after doing insertions and before changing to a new state. """ + tokens: Iterator[UnprocessedToken] if self.mode == "output": - tokens = [(0, Generic.Output, self.buffer)] + tokens = iter([(0, Generic.Output, self.buffer)]) elif self.mode == "input": tokens = self.pylexer.get_tokens_unprocessed(self.buffer) else: # traceback @@ -404,7 +432,7 @@ def buffered_tokens(self): self.buffer = "" self.insertions = [] - def get_mci(self, line): + def get_mci(self, line: str) -> tuple[Mode, str, UnprocessedToken | None]: """ Parses the line and returns a 3-tuple: (mode, code, insertion). @@ -426,10 +454,12 @@ def get_mci(self, line): """ # To reduce the number of regex match checks, we have multiple # 'if' blocks instead of 'if-elif' blocks. + mode: Mode + insertion: UnprocessedToken | None # Check for possible end of input - in2_match = self.in2_regex.match(line) - in2_match_rstrip = self.in2_regex_rstrip.match(line) + in2_match = self._in2_re.match(line) + in2_match_rstrip = self._in2_rstrip_re.match(line) if ( in2_match and in2_match.group().rstrip() == line.rstrip() ) or in2_match_rstrip: @@ -445,14 +475,10 @@ def get_mci(self, line): return mode, code, insertion # Check for output prompt - out_match = self.out_regex.match(line) - out_match_rstrip = self.out_regex_rstrip.match(line) - if out_match or out_match_rstrip: + out_match = self._out_re.match(line) or self._out_rstrip_re.match(line) + if out_match: mode = "output" - if out_match: - idx = out_match.end() - else: - idx = out_match_rstrip.end() + idx = out_match.end() code = line[idx:] # Use the 'heading' token for output. We cannot use Generic.Error # since it would conflict with exceptions. @@ -460,31 +486,26 @@ def get_mci(self, line): return mode, code, insertion # Check for input or continuation prompt (non stripped version) - in1_match = self.in1_regex.match(line) - if in1_match or (in2_match and self.mode != "tb"): - # New input or when not in tb, continued input. - # We do not check for continued input when in tb since it is - # allowable to replace a long stack with an ellipsis. + # New input or when not in tb, continued input. + # We do not check for continued input when in tb since it is + # allowable to replace a long stack with an ellipsis. + in_match = self._in1_re.match(line) or ( + in2_match if self.mode != "tb" else None + ) + if in_match: mode = "input" - if in1_match: - idx = in1_match.end() - else: # in2_match - idx = in2_match.end() + idx = in_match.end() code = line[idx:] insertion = (0, Generic.Prompt, line[:idx]) return mode, code, insertion # Check for input or continuation prompt (stripped version) - in1_match_rstrip = self.in1_regex_rstrip.match(line) - if in1_match_rstrip or (in2_match_rstrip and self.mode != "tb"): - # New input or when not in tb, continued input. - # We do not check for continued input when in tb since it is - # allowable to replace a long stack with an ellipsis. + in_match = self._in1_rstrip_re.match(line) or ( + in2_match_rstrip if self.mode != "tb" else None + ) + if in_match: mode = "input" - if in1_match_rstrip: - idx = in1_match_rstrip.end() - else: # in2_match - idx = in2_match_rstrip.end() + idx = in_match.end() code = line[idx:] insertion = (0, Generic.Prompt, line[:idx]) return mode, code, insertion @@ -521,7 +542,7 @@ def get_mci(self, line): return mode, code, insertion - def get_tokens_unprocessed(self, text): + def get_tokens_unprocessed(self, text: str) -> Iterator[UnprocessedToken]: self.reset() for match in line_re.finditer(text): line = match.group() @@ -529,16 +550,14 @@ def get_tokens_unprocessed(self, text): if mode != self.mode: # Yield buffered tokens before transitioning to new mode. - for token in self.buffered_tokens(): - yield token + yield from self.buffered_tokens() self.mode = mode if insertion: self.insertions.append((len(self.buffer), [insertion])) self.buffer += code - for token in self.buffered_tokens(): - yield token + yield from self.buffered_tokens() class IPyLexer(Lexer): @@ -557,10 +576,10 @@ class IPyLexer(Lexer): name = "IPy session" aliases = ["ipy", "ipy3"] - def __init__(self, **options): + def __init__(self, **options: Any) -> None: """ Create a new IPyLexer instance which dispatch to either an - IPythonCOnsoleLexer (if In prompts are present) or and IPythonLexer (if + IPythonConsoleLexer (if In prompts are present) or an IPythonLexer (if In prompts are not present). """ # init docstring is necessary for docs not to fail to build do to parent @@ -570,11 +589,11 @@ def __init__(self, **options): self.IPythonLexer = IPythonLexer(**options) self.IPythonConsoleLexer = IPythonConsoleLexer(**options) - def get_tokens_unprocessed(self, text): + def get_tokens_unprocessed(self, text: str) -> Iterator[UnprocessedToken]: # Search for the input prompt anywhere...this allows code blocks to # begin with comments as well. if re.match(r".*(In \[[0-9]+\]:)", text.strip(), re.DOTALL): - lex = self.IPythonConsoleLexer + lex: Lexer = self.IPythonConsoleLexer else: lex = self.IPythonLexer yield from lex.get_tokens_unprocessed(text) diff --git a/ipython_pygments_lexers/py.typed b/ipython_pygments_lexers/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/pyproject.toml b/pyproject.toml index facce4f..cde21c6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,5 +1,5 @@ [build-system] -requires = ["flit_core >=3.2,<4"] +requires = ["flit_core >=3.12,<4"] build-backend = "flit_core.buildapi" [project] @@ -8,10 +8,10 @@ authors = [ {name = "The IPython Development Team", email = "ipython-dev@python.org"}, ] readme = "README.md" -license = {file = "LICENSE"} +license = "BSD-3-Clause" +license-files = ["LICENSE"] classifiers = [ "Framework :: IPython", - "License :: OSI Approved :: BSD License", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3.11", @@ -19,10 +19,11 @@ classifiers = [ "Programming Language :: Python :: 3.13", "Programming Language :: Python :: 3.14", "Programming Language :: Python :: 3.15", + "Typing :: Typed", ] requires-python=">=3.11" dependencies = [ - "pygments" + "pygments>=2.14", ] dynamic=["version", "description"] @@ -63,12 +64,10 @@ ignore = [ [tool.mypy] python_version = "3.11" -files = ["ipython_pygments_lexers.py", "test_ipython_pygments_lexers.py"] -warn_unused_configs = true -warn_redundant_casts = true -warn_unused_ignores = true -strict_equality = true -extra_checks = true +files = ["ipython_pygments_lexers", "test_ipython_pygments_lexers.py"] +strict = true +# bygroups() and using() are untyped in types-Pygments +untyped_calls_exclude = ["pygments.lexer"] [tool.pytest.ini_options] addopts = ["-ra", "--strict-markers", "--strict-config"] diff --git a/test_ipython_pygments_lexers.py b/test_ipython_pygments_lexers.py index cb43fc6..4e22fc5 100644 --- a/test_ipython_pygments_lexers.py +++ b/test_ipython_pygments_lexers.py @@ -5,15 +5,12 @@ import pygments.lexers import pytest -from pygments import __version__ as pygments_version from pygments.lexers import BashLexer from pygments.token import Token import ipython_pygments_lexers as lexers -pyg214 = tuple(int(x) for x in pygments_version.split(".")[:2]) >= (2, 14) - -TOKEN_WS = Token.Text.Whitespace if pyg214 else Token.Text +TOKEN_WS = Token.Text.Whitespace EXPECTED_LEXER_NAMES = [ cls.name for cls in [lexers.IPythonConsoleLexer, lexers.IPython3Lexer] @@ -21,13 +18,13 @@ @pytest.mark.parametrize("expected_lexer", EXPECTED_LEXER_NAMES) -def test_pygments_entry_points(expected_lexer: str): +def test_pygments_entry_points(expected_lexer: str) -> None: """Check whether the ``entry_points`` for ``pygments.lexers`` are correct.""" all_pygments_lexer_names = {l[0] for l in pygments.lexers.get_all_lexers()} assert expected_lexer in all_pygments_lexer_names -def test_plain_python(): +def test_plain_python() -> None: lexer = lexers.IPythonLexer() fragment_2 = "x != y\n" tokens_2 = [ @@ -41,7 +38,7 @@ def test_plain_python(): assert tokens_2[:-1] == list(lexer.get_tokens(fragment_2))[:-1] -def test_shell_commands(): +def test_shell_commands() -> None: lexer = lexers.IPythonLexer() bash_lexer = BashLexer() fragment = "!echo $HOME\n" @@ -101,7 +98,7 @@ def test_shell_commands(): assert tokens_2[:-1] == list(lexer.get_tokens(fragment_2))[:-1] -def test_magics(): +def test_magics() -> None: lexer = lexers.IPythonLexer() fragment_2 = "f = %R function () {}\n" tokens_2 = [ @@ -125,7 +122,7 @@ def test_magics(): assert tokens_2[:-1] == list(lexer.get_tokens(fragment_2))[:-1] -def test_help(): +def test_help() -> None: lexer = lexers.IPythonLexer() fragment_2 = " ?math.sin\n" tokens_2 = [ @@ -145,7 +142,7 @@ def test_help(): assert tokens == list(lexer.get_tokens(fragment)) -def test_cell_magics(): +def test_cell_magics() -> None: lexer = lexers.IPythonLexer() fragment = "%%writefile -a foo.py\nif a == b:\n pass" tokens = [