From 22ef6bc68ebb32cf076c715ee7b9d5954b26e548 Mon Sep 17 00:00:00 2001 From: M Bussonnier Date: Thu, 3 Dec 2026 14:48:57 +0100 Subject: [PATCH 1/6] Add full type annotations and py.typed Turn the module into a package so it can ship py.typed (PEP 561), annotate the public API, and run mypy in strict mode. Co-Authored-By: Claude Sonnet 5.5 --- .../__init__.py | 138 ++++++++++-------- ipython_pygments_lexers/py.typed | 0 pyproject.toml | 11 +- test_ipython_pygments_lexers.py | 12 +- 4 files changed, 90 insertions(+), 71 deletions(-) rename ipython_pygments_lexers.py => ipython_pygments_lexers/__init__.py (83%) create mode 100644 ipython_pygments_lexers/py.typed diff --git a/ipython_pygments_lexers.py b/ipython_pygments_lexers/__init__.py similarity index 83% rename from ipython_pygments_lexers.py rename to ipython_pygments_lexers/__init__.py index c17c9b0..3c3bb9a 100644 --- a/ipython_pygments_lexers.py +++ b/ipython_pygments_lexers/__init__.py @@ -29,10 +29,14 @@ # The full license is in the file COPYING.txt, 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" @@ -257,7 +273,7 @@ class IPythonTracebackLexer(DelegatingLexer): 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, IPythonPartialTracebackLexer. @@ -314,14 +330,19 @@ 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 @@ -341,9 +362,9 @@ def __init__(self, **options): then 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 +379,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 +404,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 +433,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 +455,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 +476,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 +487,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 +543,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 +551,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,7 +577,7 @@ 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 @@ -570,11 +590,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..809198e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ "Programming Language :: Python :: 3.13", "Programming Language :: Python :: 3.14", "Programming Language :: Python :: 3.15", + "Typing :: Typed", ] requires-python=">=3.11" dependencies = [ @@ -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..fd20ecb 100644 --- a/test_ipython_pygments_lexers.py +++ b/test_ipython_pygments_lexers.py @@ -21,13 +21,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 +41,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 +101,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 +125,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 +145,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 = [ From 00280e0a60080294ff1956c95cfbda325e179c0e Mon Sep 17 00:00:00 2001 From: M Bussonnier Date: Thu, 3 Dec 2026 14:50:34 +0100 Subject: [PATCH 2/6] Remove Python 2 mentions and fix stale docstrings The traceback lexers no longer read a `python3` option and always use IPython3Lexer, so drop the references to Python 2.x/3.x selection. Also: - describe in1_regex/in2_regex/out_regex as strings (they are rstrip'd and compiled, so compiled patterns or None never worked) - say what IPythonTracebackLexer actually delegates to - reword the IPyLexer summary, which is not registered with Pygments - fix typos (IPythonCOnsoleLexer, "or and") Docstrings and comments only; no behaviour change. Co-Authored-By: Claude Sonnet 5.5 --- ipython_pygments_lexers/__init__.py | 41 ++++++++++++++--------------- 1 file changed, 20 insertions(+), 21 deletions(-) diff --git a/ipython_pygments_lexers/__init__.py b/ipython_pygments_lexers/__init__.py index 3c3bb9a..e93a92c 100644 --- a/ipython_pygments_lexers/__init__.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,8 +17,8 @@ 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. """ # ----------------------------------------------------------------------------- @@ -264,9 +264,8 @@ 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. # @@ -275,7 +274,7 @@ class IPythonTracebackLexer(DelegatingLexer): 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 @@ -347,19 +346,19 @@ def __init__(self, **options: Any) -> None: Parameters ---------- - in1_regex : RegexObject - The compiled regular expression used to detect the start + 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. - in2_regex : RegexObject - The compiled regular expression 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 `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: str = options.get("in1_regex", self.in1_regex) @@ -580,7 +579,7 @@ class IPyLexer(Lexer): 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 From dea106e650130a5b3844891fbb9096393faa1b03 Mon Sep 17 00:00:00 2001 From: M Bussonnier Date: Thu, 3 Dec 2026 14:50:41 +0100 Subject: [PATCH 3/6] Use PEP 639 license metadata Declare the license as the SPDX expression BSD-3-Clause with license-files, which needs flit_core >= 3.12. Drop the License :: trove classifier, which PEP 639 deprecates alongside a license expression. The built metadata now has License-Expression: BSD-3-Clause. Also fix the module header, which pointed to a nonexistent COPYING.txt, to match LICENSE (BSD 3-Clause, 2012-Present). Co-Authored-By: Claude Sonnet 5.5 --- ipython_pygments_lexers/__init__.py | 6 +++--- pyproject.toml | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/ipython_pygments_lexers/__init__.py b/ipython_pygments_lexers/__init__.py index e93a92c..37cbc47 100644 --- a/ipython_pygments_lexers/__init__.py +++ b/ipython_pygments_lexers/__init__.py @@ -22,11 +22,11 @@ """ # ----------------------------------------------------------------------------- -# 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 diff --git a/pyproject.toml b/pyproject.toml index 809198e..89d432d 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", From 2702c413d66dd8aa1de2dcfd7ddeb6d2219ef63a Mon Sep 17 00:00:00 2001 From: M Bussonnier Date: Thu, 3 Dec 2026 14:50:53 +0100 Subject: [PATCH 4/6] Require pygments >= 2.14 and test the lower bound The dependency had no lower bound, although the module does not even import on old Pygments (Python2Lexer is missing in 2.4). Require 2.14 (January 2023), the first version that emits Token.Text.Whitespace where the tests expect it, and drop the pre-2.14 shim in the tests. Add a CI job that runs the tests on Python 3.11 with pygments==2.14.0 so the floor stays accurate. Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/test.yml | 11 ++++++++++- pyproject.toml | 2 +- test_ipython_pygments_lexers.py | 5 +---- 3 files changed, 12 insertions(+), 6 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 565ac95..f30e0dc 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -44,11 +44,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,9 +69,11 @@ 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: | diff --git a/pyproject.toml b/pyproject.toml index 89d432d..cde21c6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -23,7 +23,7 @@ classifiers = [ ] requires-python=">=3.11" dependencies = [ - "pygments" + "pygments>=2.14", ] dynamic=["version", "description"] diff --git a/test_ipython_pygments_lexers.py b/test_ipython_pygments_lexers.py index fd20ecb..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] From fd9d9b7f6505686442d3c26de3880fe3005d1783 Mon Sep 17 00:00:00 2001 From: M Bussonnier Date: Thu, 3 Dec 2026 14:50:59 +0100 Subject: [PATCH 5/6] Harden the release workflow - Only version-like tags (e.g. 1.2.0, 1.2.0rc1) trigger the workflow on tag push, so a stray tag no longer publishes to PyPI. - New build job: fails on a tag that does not match __version__, builds the sdist and wheel, runs the test suite against the installed wheel (not the source tree), and uploads dist/ as an artifact. It runs on every push and PR, so packaging breakage shows up before a release. - The publish job now only downloads the artifact and uploads it, so the build no longer runs with id-token: write. - Publish runs in a "pypi" GitHub environment, so it can be gated by required reviewers or tag rules. PyPI's trusted publisher for this project has no environment configured, so it accepts this as is. The workflow file name (test.yml) is unchanged on purpose: the trusted publisher is bound to it. Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/test.yml | 52 ++++++++++++++++++++++++++++++++------ 1 file changed, 44 insertions(+), 8 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index f30e0dc..857021e 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -3,7 +3,8 @@ name: Tests on: push: branches: [ main ] - tags: [ '*' ] + # Only version tags (e.g. 1.2.0, 1.2.0rc1) trigger a release. + tags: [ '[0-9]+.[0-9]+.[0-9]+*' ] pull_request: branches: [ main ] workflow_dispatch: @@ -79,13 +80,8 @@ jobs: 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 @@ -95,12 +91,52 @@ 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: 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 + + publish: + runs-on: ubuntu-latest + if: ${{ startsWith(github.ref, 'refs/tags/') }} + needs: [lint, tests, build] + 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 From efae8f1b7dab7df9cb7c16fcd886b9544af2a163 Mon Sep 17 00:00:00 2001 From: M Bussonnier Date: Thu, 3 Dec 2026 15:09:41 +0100 Subject: [PATCH 6/6] Move PyPI publishing to its own tag-only workflow PyPI trusted publishing trusts a workflow by file name. test.yml also runs on pull requests, branch pushes and manual dispatch, and is the file contributors and Dependabot edit most, so publishing now lives in publish.yml, which only runs for version tags. publish.yml calls test.yml as a reusable workflow (lint, tests, the tag/__version__ check, building and testing the wheel), then uploads that same build from its own top-level job in the "pypi" environment. The upload has to stay in the top-level workflow: PyPI does not accept trusted-publishing uploads from inside a called workflow. test.yml gains a workflow_call trigger and loses its tag trigger and publish job. PyPI action needed after merge: add a GitHub trusted publisher with workflow publish.yml and environment pypi, then remove the old test.yml publisher. Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/publish.yml | 41 +++++++++++++++++++++++++++++++++++ .github/workflows/test.yml | 24 ++------------------ 2 files changed, 43 insertions(+), 22 deletions(-) create mode 100644 .github/workflows/publish.yml 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 857021e..59b9f63 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -3,11 +3,11 @@ name: Tests on: push: branches: [ main ] - # Only version tags (e.g. 1.2.0, 1.2.0rc1) trigger a release. - tags: [ '[0-9]+.[0-9]+.[0-9]+*' ] pull_request: branches: [ main ] workflow_dispatch: + # Called by publish.yml so a release runs the same checks and build. + workflow_call: permissions: contents: read @@ -120,23 +120,3 @@ jobs: name: dist path: dist/ if-no-files-found: error - - publish: - runs-on: ubuntu-latest - if: ${{ startsWith(github.ref, 'refs/tags/') }} - needs: [lint, tests, build] - 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