repo
stringlengths
7
90
file_url
stringlengths
81
315
file_path
stringlengths
4
228
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:38:15
2026-01-05 02:33:18
truncated
bool
2 classes
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/scripts/diff_shades_gha_helper.py
scripts/diff_shades_gha_helper.py
"""Helper script for psf/black's diff-shades Github Actions integration. diff-shades is a tool for analyzing what happens when you run Black on OSS code capturing it for comparisons or other usage. It's used here to help measure the impact of a change *before* landing it (in particular posting a comment on completion for PRs). This script exists as a more maintainable alternative to using inline Javascript in the workflow YAML files. The revision configuration and resolving, caching, and PR comment logic is contained here. For more information, please see the developer docs: https://black.readthedocs.io/en/latest/contributing/gauging_changes.html#diff-shades """ import json import os import platform import pprint import subprocess import sys import zipfile from base64 import b64encode from io import BytesIO from pathlib import Path from typing import Any, Final, Literal import click import urllib3 from packaging.version import Version COMMENT_FILE: Final = ".pr-comment.json" DIFF_STEP_NAME: Final = "Generate HTML diff report" DOCS_URL: Final = ( "https://black.readthedocs.io/en/latest/" "contributing/gauging_changes.html#diff-shades" ) USER_AGENT: Final = f"psf/black diff-shades workflow via urllib3/{urllib3.__version__}" SHA_LENGTH: Final = 10 GH_API_TOKEN: Final = os.getenv("GITHUB_TOKEN") REPO: Final = os.getenv("GITHUB_REPOSITORY", default="psf/black") http = urllib3.PoolManager() def set_output(name: str, value: str) -> None: if len(value) < 200: print(f"[INFO]: setting '{name}' to '{value}'") else: print(f"[INFO]: setting '{name}' to [{len(value)} chars]") if "GITHUB_OUTPUT" in os.environ: if "\n" in value: # https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions#multiline-strings delimiter = b64encode(os.urandom(16)).decode() value = f"{delimiter}\n{value}\n{delimiter}" command = f"{name}<<{value}" else: command = f"{name}={value}" with open(os.environ["GITHUB_OUTPUT"], "a") as f: print(command, file=f) def http_get(url: str, *, is_json: bool = True, **kwargs: Any) -> Any: headers = kwargs.get("headers") or {} headers["User-Agent"] = USER_AGENT if "github" in url: if GH_API_TOKEN: headers["Authorization"] = f"token {GH_API_TOKEN}" headers["Accept"] = "application/vnd.github.v3+json" kwargs["headers"] = headers r = http.request("GET", url, **kwargs) if is_json: data = json.loads(r.data.decode("utf-8")) else: data = r.data print(f"[INFO]: issued GET request for {r.geturl()}") if not (200 <= r.status < 300): pprint.pprint(dict(r.info())) pprint.pprint(data) raise RuntimeError(f"unexpected status code: {r.status}") return data def get_main_revision() -> str: data = http_get( f"https://api.github.com/repos/{REPO}/commits", fields={"per_page": "1", "sha": "main"}, ) assert isinstance(data[0]["sha"], str) return data[0]["sha"] def get_pr_revision(pr: int) -> str: data = http_get(f"https://api.github.com/repos/{REPO}/pulls/{pr}") assert isinstance(data["head"]["sha"], str) return data["head"]["sha"] def get_pypi_version() -> Version: data = http_get("https://pypi.org/pypi/black/json") versions = [Version(v) for v in data["releases"]] sorted_versions = sorted(versions, reverse=True) return sorted_versions[0] @click.group() def main() -> None: pass @main.command("config", help="Acquire run configuration and metadata.") @click.argument("event", type=click.Choice(["push", "pull_request"])) def config(event: Literal["push", "pull_request"]) -> None: import diff_shades # type: ignore[import-not-found] if event == "push": jobs = [{"mode": "preview-new-changes", "force-flag": "--force-preview-style"}] # Push on main, let's use PyPI Black as the baseline. baseline_name = str(get_pypi_version()) baseline_cmd = f"git checkout {baseline_name}" target_rev = os.getenv("GITHUB_SHA") assert target_rev is not None target_name = "main-" + target_rev[:SHA_LENGTH] target_cmd = f"git checkout {target_rev}" elif event == "pull_request": jobs = [ {"mode": "preview-new-changes", "force-flag": "--force-preview-style"}, {"mode": "assert-no-changes", "force-flag": "--force-stable-style"}, ] # PR, let's use main as the baseline. baseline_rev = get_main_revision() baseline_name = "main-" + baseline_rev[:SHA_LENGTH] baseline_cmd = f"git checkout {baseline_rev}" pr_ref = os.getenv("GITHUB_REF") assert pr_ref is not None pr_num = int(pr_ref[10:-6]) pr_rev = get_pr_revision(pr_num) target_name = f"pr-{pr_num}-{pr_rev[:SHA_LENGTH]}" target_cmd = f"gh pr checkout {pr_num} && git merge origin/main" env = f"{platform.system()}-{platform.python_version()}-{diff_shades.__version__}" for entry in jobs: entry["baseline-analysis"] = f"{entry['mode']}-{baseline_name}.json" entry["baseline-setup-cmd"] = baseline_cmd entry["target-analysis"] = f"{entry['mode']}-{target_name}.json" entry["target-setup-cmd"] = target_cmd entry["baseline-cache-key"] = f"{env}-{baseline_name}-{entry['mode']}" if event == "pull_request": # These are only needed for the PR comment. entry["baseline-sha"] = baseline_rev entry["target-sha"] = pr_rev set_output("matrix", json.dumps(jobs, indent=None)) pprint.pprint(jobs) @main.command("comment-body", help="Generate the body for a summary PR comment.") @click.argument("baseline", type=click.Path(exists=True, path_type=Path)) @click.argument("target", type=click.Path(exists=True, path_type=Path)) @click.argument("baseline-sha") @click.argument("target-sha") @click.argument("pr-num", type=int) def comment_body( baseline: Path, target: Path, baseline_sha: str, target_sha: str, pr_num: int ) -> None: # fmt: off cmd = [ sys.executable, "-m", "diff_shades", "--no-color", "compare", str(baseline), str(target), "--quiet", "--check" ] # fmt: on proc = subprocess.run(cmd, stdout=subprocess.PIPE, encoding="utf-8") if not proc.returncode: body = ( f"**diff-shades** reports zero changes comparing this PR ({target_sha}) to" f" main ({baseline_sha}).\n\n---\n\n" ) else: body = ( f"**diff-shades** results comparing this PR ({target_sha}) to main" f" ({baseline_sha}). The full diff is [available in the logs]" f'($job-diff-url) under the "{DIFF_STEP_NAME}" step.' ) body += "\n```text\n" + proc.stdout.strip() + "\n```\n" body += ( f"[**What is this?**]({DOCS_URL}) | [Workflow run]($workflow-run-url) |" " [diff-shades documentation](https://github.com/ichard26/diff-shades#readme)" ) print(f"[INFO]: writing comment details to {COMMENT_FILE}") with open(COMMENT_FILE, "w", encoding="utf-8") as f: json.dump({"body": body, "pr-number": pr_num}, f) @main.command("comment-details", help="Get PR comment resources from a workflow run.") @click.argument("run-id") def comment_details(run_id: str) -> None: data = http_get(f"https://api.github.com/repos/{REPO}/actions/runs/{run_id}") if data["event"] != "pull_request" or data["conclusion"] == "cancelled": set_output("needs-comment", "false") return set_output("needs-comment", "true") jobs = http_get(data["jobs_url"])["jobs"] job = next(j for j in jobs if j["name"] == "compare / preview-new-changes") diff_step = next(s for s in job["steps"] if s["name"] == DIFF_STEP_NAME) diff_url = job["html_url"] + f"#step:{diff_step['number']}:1" artifacts = http_get(data["artifacts_url"])["artifacts"] comment_artifact = next(a for a in artifacts if a["name"] == COMMENT_FILE) comment_url = comment_artifact["archive_download_url"] comment_zip = BytesIO(http_get(comment_url, is_json=False)) with zipfile.ZipFile(comment_zip) as zfile: with zfile.open(COMMENT_FILE) as rf: comment_data = json.loads(rf.read().decode("utf-8")) set_output("pr-number", str(comment_data["pr-number"])) body = comment_data["body"] # It's more convenient to fill in these fields after the first workflow is done # since this command can access the workflows API (doing it in the main workflow # while it's still in progress seems impossible). body = body.replace("$workflow-run-url", data["html_url"]) body = body.replace("$job-diff-url", diff_url) set_output("comment-body", body) if __name__ == "__main__": main()
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/scripts/check_version_in_basics_example.py
scripts/check_version_in_basics_example.py
""" Check that the rev value in the example from ``the_basics.md`` matches the latest version of Black. This saves us from forgetting to update that during the release process. """ import os import sys import commonmark from bs4 import BeautifulSoup def main(changes: str, the_basics: str) -> None: changes_html = commonmark.commonmark(changes) changes_soup = BeautifulSoup(changes_html, "html.parser") headers = changes_soup.find_all("h2") tags = [header.string for header in headers if header.string != "Unreleased"] latest_tag = tags[0] the_basics_html = commonmark.commonmark(the_basics) the_basics_soup = BeautifulSoup(the_basics_html, "html.parser") version_examples = [ code_block.string for code_block in the_basics_soup.find_all(class_="language-console") if "$ black --version" in code_block.string # type: ignore[operator] ] for tag in tags: for version_example in version_examples: if tag in version_example and tag != latest_tag: # type: ignore[operator] print( "Please set the version in the ``black --version`` " "examples from ``the_basics.md`` to be the latest one.\n" f"Expected {latest_tag}, got {tag}.\n" ) sys.exit(1) if __name__ == "__main__": with open("CHANGES.md", encoding="utf-8") as fd: changes = fd.read() with open( os.path.join("docs", "usage_and_configuration", "the_basics.md"), encoding="utf-8", ) as fd: the_basics = fd.read() main(changes, the_basics)
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/scripts/fuzz.py
scripts/fuzz.py
"""Property-based tests for Black. By Zac Hatfield-Dodds, based on my Hypothesmith tool for source code generation. You can run this file with `python`, `pytest`, or (soon) a coverage-guided fuzzer I'm working on. """ import hypothesmith from hypothesis import HealthCheck, given, settings from hypothesis import strategies as st import black # This test uses the Hypothesis and Hypothesmith libraries to generate random # syntatically-valid Python source code and run Black in odd modes. @settings( max_examples=1000, # roughly 1k tests/minute, or half that under coverage derandomize=True, # deterministic mode to avoid CI flakiness deadline=None, # ignore Hypothesis' health checks; we already know that suppress_health_check=list(HealthCheck), # this is slow and filter-heavy. ) @given( # Note that while Hypothesmith might generate code unlike that written by # humans, it's a general test that should pass for any *valid* source code. # (so e.g. running it against code scraped of the internet might also help) src_contents=hypothesmith.from_grammar() | hypothesmith.from_node(), # Using randomly-varied modes helps us to exercise less common code paths. mode=st.builds( black.FileMode, line_length=st.just(88) | st.integers(0, 200), string_normalization=st.booleans(), preview=st.booleans(), is_pyi=st.booleans(), magic_trailing_comma=st.booleans(), ), ) def test_idempotent_any_syntatically_valid_python( src_contents: str, mode: black.FileMode ) -> None: if ( "#\r" in src_contents or "\\\n" in src_contents ) and black.Preview.normalize_cr_newlines not in mode: return # Before starting, let's confirm that the input string is valid Python: compile(src_contents, "<string>", "exec") # else the bug is in hypothesmith # Then format the code... dst_contents = black.format_str(src_contents, mode=mode) # And check that we got equivalent and stable output. black.assert_equivalent(src_contents, dst_contents) black.assert_stable(src_contents, dst_contents, mode=mode) # Future test: check that pure-python and mypyc versions of black # give identical output for identical input? if __name__ == "__main__": # Run tests, including shrinking and reporting any known failures. test_idempotent_any_syntatically_valid_python() # If Atheris is available, run coverage-guided fuzzing. # (if you want only bounded fuzzing, just use `pytest fuzz.py`) try: import sys import atheris except ImportError: pass else: test = test_idempotent_any_syntatically_valid_python atheris.Setup( sys.argv, test.hypothesis.fuzz_one_input, # type: ignore[attr-defined] ) atheris.Fuzz()
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/scripts/generate_schema.py
scripts/generate_schema.py
import json from typing import IO, Any import click import black def generate_schema_from_click( cmd: click.Command, ) -> dict[str, Any]: result: dict[str, dict[str, Any]] = {} for param in cmd.params: if not isinstance(param, click.Option) or param.is_eager: continue assert param.name name = param.name.replace("_", "-") result[name] = {} match param.type: case click.types.IntParamType(): result[name]["type"] = "integer" case click.types.StringParamType() | click.types.Path(): result[name]["type"] = "string" case click.types.Choice(choices=choices): result[name]["enum"] = choices case click.types.BoolParamType(): result[name]["type"] = "boolean" case _: msg = f"{param.type!r} not a known type for {param}" raise TypeError(msg) if param.multiple: result[name] = {"type": "array", "items": result[name]} result[name]["description"] = param.help default = param.to_info_dict()["default"] if default is not None and not param.multiple: result[name]["default"] = default return result @click.command(context_settings={"help_option_names": ["-h", "--help"]}) @click.option("--schemastore", is_flag=True, help="SchemaStore format") @click.option("--outfile", type=click.File(mode="w"), help="Write to file") def main(schemastore: bool, outfile: IO[str]) -> None: properties = generate_schema_from_click(black.main) del properties["line-ranges"] schema: dict[str, Any] = { "$schema": "http://json-schema.org/draft-07/schema#", "$id": ( "https://github.com/psf/black/blob/main/src/black/resources/black.schema.json" ), "$comment": "tool.black table in pyproject.toml", "type": "object", "additionalProperties": False, "properties": properties, } if schemastore: schema["$id"] = "https://json.schemastore.org/partial-black.json" # The precise list of unstable features may change frequently, so don't # bother putting it in SchemaStore schema["properties"]["enable-unstable-feature"]["items"] = {"type": "string"} print(json.dumps(schema, indent=2), file=outfile) if __name__ == "__main__": main()
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/scripts/check_pre_commit_rev_in_example.py
scripts/check_pre_commit_rev_in_example.py
""" Check that the rev value in the example pre-commit configuration matches the latest version of Black. This saves us from forgetting to update that during the release process. Why can't we just use `rev: stable` and call it a day? Well pre-commit won't auto update the hook as you may expect (and for good reasons, some technical and some pragmatic). Encouraging bad practice is also just not ideal. xref: https://github.com/psf/black/issues/420 """ import os import sys import commonmark import yaml from bs4 import BeautifulSoup def main(changes: str, source_version_control: str) -> None: changes_html = commonmark.commonmark(changes) changes_soup = BeautifulSoup(changes_html, "html.parser") headers = changes_soup.find_all("h2") latest_tag, *_ = ( header.string for header in headers if header.string != "Unreleased" ) source_version_control_html = commonmark.commonmark(source_version_control) source_version_control_soup = BeautifulSoup( source_version_control_html, "html.parser" ) pre_commit_repos = yaml.safe_load( source_version_control_soup.find(class_="language-yaml").string # type: ignore[union-attr, arg-type] )["repos"] for repo in pre_commit_repos: pre_commit_rev = repo["rev"] if not pre_commit_rev == latest_tag: print( "Please set the rev in ``source_version_control.md`` to be the latest " f"one.\nExpected {latest_tag}, got {pre_commit_rev}.\n" ) sys.exit(1) if __name__ == "__main__": with open("CHANGES.md", encoding="utf-8") as fd: changes = fd.read() with open( os.path.join("docs", "integrations", "source_version_control.md"), encoding="utf-8", ) as fd: source_version_control = fd.read() main(changes, source_version_control)
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/scripts/release_tests.py
scripts/release_tests.py
#!/usr/bin/env python3 import unittest from pathlib import Path from shutil import rmtree from tempfile import TemporaryDirectory from typing import Any from unittest.mock import Mock, patch from release import SourceFiles, tuple_calver # type: ignore class FakeDateTime: """Used to mock the date to test generating next calver function""" def today(*args: Any, **kwargs: Any) -> "FakeDateTime": # noqa: B902 return FakeDateTime() # Add leading 0 on purpose to ensure we remove it def strftime(*args: Any, **kwargs: Any) -> str: # noqa: B902 return "69.01" class TestRelease(unittest.TestCase): def setUp(self) -> None: # We only test on >= 3.12 self.tempdir = TemporaryDirectory(delete=False) # type: ignore self.tempdir_path = Path(self.tempdir.name) self.sf = SourceFiles(self.tempdir_path) def tearDown(self) -> None: rmtree(self.tempdir.name) return super().tearDown() @patch("release.get_git_tags") def test_get_current_version(self, mocked_git_tags: Mock) -> None: mocked_git_tags.return_value = ["1.1.0", "69.1.0", "69.1.1", "2.2.0"] self.assertEqual("69.1.1", self.sf.get_current_version()) @patch("release.get_git_tags") @patch("release.datetime", FakeDateTime) def test_get_next_version(self, mocked_git_tags: Mock) -> None: # test we handle no args mocked_git_tags.return_value = [] self.assertEqual( "69.1.0", self.sf.get_next_version(), "Unable to get correct next version with no git tags", ) # test we handle mocked_git_tags.return_value = ["1.1.0", "69.1.0", "69.1.1", "2.2.0"] self.assertEqual( "69.1.2", self.sf.get_next_version(), "Unable to get correct version with 2 previous versions released this" " month", ) def test_tuple_calver(self) -> None: first_month_release = tuple_calver("69.1.0") second_month_release = tuple_calver("69.1.1") self.assertEqual((69, 1, 0), first_month_release) self.assertEqual((0, 0, 0), tuple_calver("69.1.1a0")) # Hack for alphas/betas self.assertTrue(first_month_release < second_month_release) if __name__ == "__main__": unittest.main()
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/scripts/__init__.py
scripts/__init__.py
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/scripts/release.py
scripts/release.py
#!/usr/bin/env python3 """ Tool to help automate changes needed in commits during and after releases """ from __future__ import annotations import argparse import logging import re import sys from datetime import datetime from pathlib import Path from subprocess import run LOG = logging.getLogger(__name__) NEW_VERSION_CHANGELOG_TEMPLATE = """\ ## Unreleased <!-- PR authors: Please include the PR number in the changelog entry, not the issue number --> ### Highlights <!-- Include any especially major or disruptive changes here --> ### Stable style <!-- Changes that affect Black's stable style --> ### Preview style <!-- Changes that affect Black's preview style --> ### Configuration <!-- Changes to how Black can be configured --> ### Packaging <!-- Changes to how Black is packaged, such as dependency requirements --> ### Parser <!-- Changes to the parser or to version autodetection --> ### Performance <!-- Changes that improve Black's performance. --> ### Output <!-- Changes to Black's terminal output and error messages --> ### _Blackd_ <!-- Changes to blackd --> ### Integrations <!-- For example, Docker, GitHub Actions, pre-commit, editors --> ### Documentation <!-- Major changes to documentation and policies. Small docs changes don't need a changelog entry. --> """ class NoGitTagsError(Exception): ... # TODO: Do better with alpha + beta releases # Maybe we vendor packaging library def get_git_tags(versions_only: bool = True) -> list[str]: """Pull out all tags or calvers only""" cp = run(["git", "tag"], capture_output=True, check=True, encoding="utf8") if not cp.stdout: LOG.error(f"Returned no git tags stdout: {cp.stderr}") raise NoGitTagsError git_tags = cp.stdout.splitlines() if versions_only: return [t for t in git_tags if t[0].isdigit()] return git_tags # TODO: Support sorting alhpa/beta releases correctly def tuple_calver(calver: str) -> tuple[int, ...]: # mypy can't notice maxsplit below """Convert a calver string into a tuple of ints for sorting""" try: return tuple(map(int, calver.split(".", maxsplit=2))) except ValueError: return (0, 0, 0) class SourceFiles: def __init__(self, black_repo_dir: Path): # File path fun all pathlib to be platform agnostic self.black_repo_path = black_repo_dir self.changes_path = self.black_repo_path / "CHANGES.md" self.docs_path = self.black_repo_path / "docs" self.version_doc_paths = ( self.docs_path / "integrations" / "source_version_control.md", self.docs_path / "usage_and_configuration" / "the_basics.md", ) self.current_version = self.get_current_version() self.next_version = self.get_next_version() def __str__(self) -> str: return f"""\ > SourceFiles ENV: Repo path: {self.black_repo_path} CHANGES.md path: {self.changes_path} docs path: {self.docs_path} Current version: {self.current_version} Next version: {self.next_version} """ def add_template_to_changes(self) -> int: """Add the template to CHANGES.md if it does not exist""" LOG.info(f"Adding template to {self.changes_path}") with self.changes_path.open("r", encoding="utf-8") as cfp: changes_string = cfp.read() if "## Unreleased" in changes_string: LOG.error(f"{self.changes_path} already has unreleased template") return 1 templated_changes_string = changes_string.replace( "# Change Log\n", f"# Change Log\n\n{NEW_VERSION_CHANGELOG_TEMPLATE}", ) with self.changes_path.open("w", encoding="utf-8") as cfp: cfp.write(templated_changes_string) LOG.info(f"Added template to {self.changes_path}") return 0 def cleanup_changes_template_for_release(self) -> None: LOG.info(f"Cleaning up {self.changes_path}") with self.changes_path.open("r", encoding="utf-8") as cfp: changes_string = cfp.read() # Change Unreleased to next version changes_string = changes_string.replace( "## Unreleased", f"## {self.next_version}" ) # Remove all comments changes_string = re.sub(r"(?m)^<!--(?>(?:.|\n)*?-->)\n\n", "", changes_string) # Remove empty subheadings changes_string = re.sub(r"(?m)^###.+\n\n(?=#)", "", changes_string) with self.changes_path.open("w", encoding="utf-8") as cfp: cfp.write(changes_string) LOG.debug(f"Finished Cleaning up {self.changes_path}") def get_current_version(self) -> str: """Get the latest git (version) tag as latest version""" return sorted(get_git_tags(), key=lambda k: tuple_calver(k))[-1] def get_next_version(self) -> str: """Workout the year and month + version number we need to move to""" base_calver = datetime.today().strftime("%y.%m") calver_parts = base_calver.split(".") base_calver = f"{calver_parts[0]}.{int(calver_parts[1])}" # Remove leading 0 git_tags = get_git_tags() same_month_releases = [ t for t in git_tags if t.startswith(base_calver) and "a" not in t ] if len(same_month_releases) < 1: return f"{base_calver}.0" same_month_version = same_month_releases[-1].split(".", 2)[-1] return f"{base_calver}.{int(same_month_version) + 1}" def update_repo_for_release(self) -> int: """Update CHANGES.md + doc files ready for release""" self.cleanup_changes_template_for_release() self.update_version_in_docs() return 0 # return 0 if no exceptions hit def update_version_in_docs(self) -> None: for doc_path in self.version_doc_paths: LOG.info(f"Updating black version to {self.next_version} in {doc_path}") with doc_path.open("r", encoding="utf-8") as dfp: doc_string = dfp.read() next_version_doc = doc_string.replace( self.current_version, self.next_version ) with doc_path.open("w", encoding="utf-8") as dfp: dfp.write(next_version_doc) LOG.debug( f"Finished updating black version to {self.next_version} in {doc_path}" ) def _handle_debug(debug: bool) -> None: """Turn on debugging if asked otherwise INFO default""" log_level = logging.DEBUG if debug else logging.INFO logging.basicConfig( format="[%(asctime)s] %(levelname)s: %(message)s (%(filename)s:%(lineno)d)", level=log_level, ) def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser() parser.add_argument( "-a", "--add-changes-template", action="store_true", help="Add the Unreleased template to CHANGES.md", ) parser.add_argument( "-d", "--debug", action="store_true", help="Verbose debug output" ) args = parser.parse_args() _handle_debug(args.debug) return args def main() -> int: args = parse_args() # Need parent.parent cause script is in scripts/ directory sf = SourceFiles(Path(__file__).parent.parent) if args.add_changes_template: return sf.add_template_to_changes() LOG.info(f"Current version detected to be {sf.current_version}") LOG.info(f"Next version will be {sf.next_version}") return sf.update_repo_for_release() if __name__ == "__main__": # pragma: no cover sys.exit(main())
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/gallery/gallery.py
gallery/gallery.py
import atexit import json import subprocess import tarfile import tempfile import traceback import venv import zipfile from argparse import ArgumentParser, Namespace from collections.abc import Generator from concurrent.futures import ThreadPoolExecutor from functools import lru_cache, partial from pathlib import Path from typing import NamedTuple, Union, cast from urllib.request import urlopen, urlretrieve PYPI_INSTANCE = "https://pypi.org/pypi" PYPI_TOP_PACKAGES = ( "https://hugovk.github.io/top-pypi-packages/top-pypi-packages.min.json" ) INTERNAL_BLACK_REPO = f"{tempfile.gettempdir()}/__black" ArchiveKind = Union[tarfile.TarFile, zipfile.ZipFile] subprocess.run = partial(subprocess.run, check=True) # type: ignore # https://github.com/python/mypy/issues/1484 class BlackVersion(NamedTuple): version: str config: str | None = None def get_pypi_download_url(package: str, version: str | None) -> str: with urlopen(PYPI_INSTANCE + f"/{package}/json") as page: metadata = json.load(page) if version is None: sources = metadata["urls"] else: if version in metadata["releases"]: sources = metadata["releases"][version] else: raise ValueError( f"No releases found with version ('{version}') tag. " f"Found releases: {metadata['releases'].keys()}" ) for source in sources: if source["python_version"] == "source": break else: raise ValueError(f"Couldn't find any sources for {package}") return cast(str, source["url"]) def get_top_packages() -> list[str]: with urlopen(PYPI_TOP_PACKAGES) as page: result = json.load(page) return [package["project"] for package in result["rows"]] def get_package_source(package: str, version: str | None) -> str: if package == "cpython": if version is None: version = "main" return f"https://github.com/python/cpython/archive/{version}.zip" elif package == "pypy": if version is None: version = "branch/default" return ( f"https://foss.heptapod.net/pypy/pypy/repository/{version}/archive.tar.bz2" ) else: return get_pypi_download_url(package, version) def get_archive_manager(local_file: str) -> ArchiveKind: if tarfile.is_tarfile(local_file): return tarfile.open(local_file) elif zipfile.is_zipfile(local_file): return zipfile.ZipFile(local_file) else: raise ValueError("Unknown archive kind.") def get_first_archive_member(archive: ArchiveKind) -> str: if isinstance(archive, tarfile.TarFile): return archive.getnames()[0] elif isinstance(archive, zipfile.ZipFile): return archive.namelist()[0] def download_and_extract(package: str, version: str | None, directory: Path) -> Path: source = get_package_source(package, version) local_file, _ = urlretrieve(source, directory / f"{package}-src") with get_archive_manager(local_file) as archive: archive.extractall(path=directory) result_dir = get_first_archive_member(archive) return directory / result_dir def get_package(package: str, version: str | None, directory: Path) -> Path | None: try: return download_and_extract(package, version, directory) except Exception: print(f"Caught an exception while downloading {package}.") traceback.print_exc() return None DEFAULT_SLICE = slice(None) # for flake8 def download_and_extract_top_packages( directory: Path, workers: int = 8, limit: slice = DEFAULT_SLICE, ) -> Generator[Path, None, None]: with ThreadPoolExecutor(max_workers=workers) as executor: bound_downloader = partial(get_package, version=None, directory=directory) for package in executor.map(bound_downloader, get_top_packages()[limit]): if package is not None: yield package def git_create_repository(repo: Path) -> None: subprocess.run(["git", "init"], cwd=repo) git_add_and_commit(msg="Initial commit", repo=repo) def git_add_and_commit(msg: str, repo: Path) -> None: subprocess.run(["git", "add", "."], cwd=repo) subprocess.run(["git", "commit", "-m", msg, "--allow-empty"], cwd=repo) def git_switch_branch( branch: str, repo: Path, new: bool = False, from_branch: str | None = None ) -> None: args = ["git", "checkout"] if new: args.append("-b") args.append(branch) if from_branch: args.append(from_branch) subprocess.run(args, cwd=repo) def init_repos(options: Namespace) -> tuple[Path, ...]: options.output.mkdir(exist_ok=True) if options.top_packages: source_directories = tuple( download_and_extract_top_packages( directory=options.output, workers=options.workers, limit=slice(None, options.top_packages), ) ) else: source_directories = ( download_and_extract( package=options.pypi_package, version=options.version, directory=options.output, ), ) for source_directory in source_directories: git_create_repository(source_directory) if options.black_repo is None: subprocess.run( ["git", "clone", "https://github.com/psf/black.git", INTERNAL_BLACK_REPO], cwd=options.output, ) options.black_repo = options.output / INTERNAL_BLACK_REPO return source_directories @lru_cache(8) def black_runner(version: str, black_repo: Path) -> Path: directory = tempfile.TemporaryDirectory() venv.create(directory.name, with_pip=True) python = Path(directory.name) / "bin" / "python" subprocess.run([python, "-m", "pip", "install", "-e", black_repo]) atexit.register(directory.cleanup) return python def format_repo_with_version( repo: Path, from_branch: str | None, black_repo: Path, black_version: BlackVersion, input_directory: Path, ) -> str: current_branch = f"black-{black_version.version}" git_switch_branch(black_version.version, repo=black_repo) git_switch_branch(current_branch, repo=repo, new=True, from_branch=from_branch) format_cmd: list[Path | str] = [ black_runner(black_version.version, black_repo), (black_repo / "black.py").resolve(), ".", ] if black_version.config: format_cmd.extend(["--config", input_directory / black_version.config]) subprocess.run(format_cmd, cwd=repo, check=False) # ensure the process # continuess to run even it can't format some files. Reporting those # should be enough git_add_and_commit(f"Format with black:{black_version.version}", repo=repo) return current_branch def format_repos(repos: tuple[Path, ...], options: Namespace) -> None: black_versions = tuple( BlackVersion(*version.split(":")) for version in options.versions ) for repo in repos: from_branch = None for black_version in black_versions: from_branch = format_repo_with_version( repo=repo, from_branch=from_branch, black_repo=options.black_repo, black_version=black_version, input_directory=options.input, ) git_switch_branch("main", repo=repo) git_switch_branch("main", repo=options.black_repo) def main() -> None: parser = ArgumentParser(description="""Black Gallery is a script that automates the process of applying different Black versions to a selected PyPI package and seeing the results between versions.""") group = parser.add_mutually_exclusive_group(required=True) group.add_argument("-p", "--pypi-package", help="PyPI package to download.") group.add_argument( "-t", "--top-packages", help="Top n PyPI packages to download.", type=int ) parser.add_argument("-b", "--black-repo", help="Black's Git repository.", type=Path) parser.add_argument( "-v", "--version", help=( "Version for given PyPI package. Will be discarded if used with -t option." ), ) parser.add_argument( "-w", "--workers", help=( "Maximum number of threads to download with at the same time. " "Will be discarded if used with -p option." ), ) parser.add_argument( "-i", "--input", default=Path("/input"), type=Path, help="Input directory to read configuration.", ) parser.add_argument( "-o", "--output", default=Path("/output"), type=Path, help="Output directory to download and put result artifacts.", ) parser.add_argument("versions", nargs="*", default=("main",), help="") options = parser.parse_args() repos = init_repos(options) format_repos(repos, options) if __name__ == "__main__": main()
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/src/blib2to3/pytree.py
src/blib2to3/pytree.py
# Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """ Python parse tree definitions. This is a very concrete parse tree; we need to keep every token and even the comments and whitespace between tokens. There's also a pattern matching implementation here. """ # mypy: allow-untyped-defs, allow-incomplete-defs from collections.abc import Iterable, Iterator from typing import Any, Optional, TypeVar, Union from blib2to3.pgen2.grammar import Grammar __author__ = "Guido van Rossum <guido@python.org>" import sys from io import StringIO HUGE: int = 0x7FFFFFFF # maximum repeat count, default max _type_reprs: dict[int, str | int] = {} def type_repr(type_num: int) -> str | int: global _type_reprs if not _type_reprs: from . import pygram if not hasattr(pygram, "python_symbols"): pygram.initialize(cache_dir=None) # printing tokens is possible but not as useful # from .pgen2 import token // token.__dict__.items(): for name in dir(pygram.python_symbols): val = getattr(pygram.python_symbols, name) if type(val) == int: _type_reprs[val] = name return _type_reprs.setdefault(type_num, type_num) _P = TypeVar("_P", bound="Base") NL = Union["Node", "Leaf"] Context = tuple[str, tuple[int, int]] RawNode = tuple[int, Optional[str], Optional[Context], Optional[list[NL]]] class Base: """ Abstract base class for Node and Leaf. This provides some default functionality and boilerplate using the template pattern. A node may be a subnode of at most one parent. """ # Default values for instance variables type: int # int: token number (< 256) or symbol number (>= 256) parent: Optional["Node"] = None # Parent node pointer, or None children: list[NL] # List of subnodes was_changed: bool = False was_checked: bool = False def __new__(cls, *args, **kwds): """Constructor that prevents Base from being instantiated.""" assert cls is not Base, "Cannot instantiate Base" return object.__new__(cls) def __eq__(self, other: Any) -> bool: """ Compare two nodes for equality. This calls the method _eq(). """ if self.__class__ is not other.__class__: return NotImplemented return self._eq(other) @property def prefix(self) -> str: raise NotImplementedError def _eq(self: _P, other: _P) -> bool: """ Compare two nodes for equality. This is called by __eq__ and __ne__. It is only called if the two nodes have the same type. This must be implemented by the concrete subclass. Nodes should be considered equal if they have the same structure, ignoring the prefix string and other context information. """ raise NotImplementedError def __deepcopy__(self: _P, memo: Any) -> _P: return self.clone() def clone(self: _P) -> _P: """ Return a cloned (deep) copy of self. This must be implemented by the concrete subclass. """ raise NotImplementedError def post_order(self) -> Iterator[NL]: """ Return a post-order iterator for the tree. This must be implemented by the concrete subclass. """ raise NotImplementedError def pre_order(self) -> Iterator[NL]: """ Return a pre-order iterator for the tree. This must be implemented by the concrete subclass. """ raise NotImplementedError def replace(self, new: NL | list[NL]) -> None: """Replace this node with a new one in the parent.""" assert self.parent is not None, str(self) assert new is not None if not isinstance(new, list): new = [new] l_children = [] found = False for ch in self.parent.children: if ch is self: assert not found, (self.parent.children, self, new) if new is not None: l_children.extend(new) found = True else: l_children.append(ch) assert found, (self.children, self, new) self.parent.children = l_children self.parent.changed() self.parent.invalidate_sibling_maps() for x in new: x.parent = self.parent self.parent = None def get_lineno(self) -> int | None: """Return the line number which generated the invocant node.""" node = self while not isinstance(node, Leaf): if not node.children: return None node = node.children[0] return node.lineno def changed(self) -> None: if self.was_changed: return if self.parent: self.parent.changed() self.was_changed = True def remove(self) -> int | None: """ Remove the node from the tree. Returns the position of the node in its parent's children before it was removed. """ if self.parent: for i, node in enumerate(self.parent.children): if node is self: del self.parent.children[i] self.parent.changed() self.parent.invalidate_sibling_maps() self.parent = None return i return None @property def next_sibling(self) -> NL | None: """ The node immediately following the invocant in their parent's children list. If the invocant does not have a next sibling, it is None """ if self.parent is None: return None if self.parent.next_sibling_map is None: self.parent.update_sibling_maps() assert self.parent.next_sibling_map is not None return self.parent.next_sibling_map[id(self)] @property def prev_sibling(self) -> NL | None: """ The node immediately preceding the invocant in their parent's children list. If the invocant does not have a previous sibling, it is None. """ if self.parent is None: return None if self.parent.prev_sibling_map is None: self.parent.update_sibling_maps() assert self.parent.prev_sibling_map is not None return self.parent.prev_sibling_map[id(self)] def leaves(self) -> Iterator["Leaf"]: for child in self.children: yield from child.leaves() def depth(self) -> int: if self.parent is None: return 0 return 1 + self.parent.depth() def get_suffix(self) -> str: """ Return the string immediately following the invocant node. This is effectively equivalent to node.next_sibling.prefix """ next_sib = self.next_sibling if next_sib is None: return "" prefix = next_sib.prefix return prefix class Node(Base): """Concrete implementation for interior nodes.""" fixers_applied: list[Any] | None used_names: set[str] | None def __init__( self, type: int, children: list[NL], context: Any | None = None, prefix: str | None = None, fixers_applied: list[Any] | None = None, ) -> None: """ Initializer. Takes a type constant (a symbol number >= 256), a sequence of child nodes, and an optional context keyword argument. As a side effect, the parent pointers of the children are updated. """ assert type >= 256, type self.type = type self.children = list(children) for ch in self.children: assert ch.parent is None, repr(ch) ch.parent = self self.invalidate_sibling_maps() if prefix is not None: self.prefix = prefix if fixers_applied: self.fixers_applied = fixers_applied[:] else: self.fixers_applied = None def __repr__(self) -> str: """Return a canonical string representation.""" assert self.type is not None return f"{self.__class__.__name__}({type_repr(self.type)}, {self.children!r})" def __str__(self) -> str: """ Return a pretty string representation. This reproduces the input source exactly. """ return "".join(map(str, self.children)) def _eq(self, other: Base) -> bool: """Compare two nodes for equality.""" return (self.type, self.children) == (other.type, other.children) def clone(self) -> "Node": assert self.type is not None """Return a cloned (deep) copy of self.""" return Node( self.type, [ch.clone() for ch in self.children], fixers_applied=self.fixers_applied, ) def post_order(self) -> Iterator[NL]: """Return a post-order iterator for the tree.""" for child in self.children: yield from child.post_order() yield self def pre_order(self) -> Iterator[NL]: """Return a pre-order iterator for the tree.""" yield self for child in self.children: yield from child.pre_order() @property def prefix(self) -> str: """ The whitespace and comments preceding this node in the input. """ if not self.children: return "" return self.children[0].prefix @prefix.setter def prefix(self, prefix: str) -> None: if self.children: self.children[0].prefix = prefix def set_child(self, i: int, child: NL) -> None: """ Equivalent to 'node.children[i] = child'. This method also sets the child's parent attribute appropriately. """ child.parent = self self.children[i].parent = None self.children[i] = child self.changed() self.invalidate_sibling_maps() def insert_child(self, i: int, child: NL) -> None: """ Equivalent to 'node.children.insert(i, child)'. This method also sets the child's parent attribute appropriately. """ child.parent = self self.children.insert(i, child) self.changed() self.invalidate_sibling_maps() def append_child(self, child: NL) -> None: """ Equivalent to 'node.children.append(child)'. This method also sets the child's parent attribute appropriately. """ child.parent = self self.children.append(child) self.changed() self.invalidate_sibling_maps() def invalidate_sibling_maps(self) -> None: self.prev_sibling_map: dict[int, NL | None] | None = None self.next_sibling_map: dict[int, NL | None] | None = None def update_sibling_maps(self) -> None: _prev: dict[int, NL | None] = {} _next: dict[int, NL | None] = {} self.prev_sibling_map = _prev self.next_sibling_map = _next previous: NL | None = None for current in self.children: _prev[id(current)] = previous _next[id(previous)] = current previous = current _next[id(current)] = None class Leaf(Base): """Concrete implementation for leaf nodes.""" # Default values for instance variables value: str fixers_applied: list[Any] bracket_depth: int # Changed later in brackets.py opening_bracket: Optional["Leaf"] = None used_names: set[str] | None _prefix = "" # Whitespace and comments preceding this token in the input lineno: int = 0 # Line where this token starts in the input column: int = 0 # Column where this token starts in the input # If not None, this Leaf is created by converting a block of fmt off/skip # code, and `fmt_pass_converted_first_leaf` points to the first Leaf in the # converted code. fmt_pass_converted_first_leaf: Optional["Leaf"] = None def __init__( self, type: int, value: str, context: Context | None = None, prefix: str | None = None, fixers_applied: list[Any] = [], opening_bracket: Optional["Leaf"] = None, fmt_pass_converted_first_leaf: Optional["Leaf"] = None, ) -> None: """ Initializer. Takes a type constant (a token number < 256), a string value, and an optional context keyword argument. """ assert 0 <= type < 256, type if context is not None: self._prefix, (self.lineno, self.column) = context self.type = type self.value = value if prefix is not None: self._prefix = prefix self.fixers_applied: list[Any] | None = fixers_applied[:] self.children = [] self.opening_bracket = opening_bracket self.fmt_pass_converted_first_leaf = fmt_pass_converted_first_leaf def __repr__(self) -> str: """Return a canonical string representation.""" from .pgen2.token import tok_name assert self.type is not None return ( f"{self.__class__.__name__}({tok_name.get(self.type, self.type)}," f" {self.value!r})" ) def __str__(self) -> str: """ Return a pretty string representation. This reproduces the input source exactly. """ return self._prefix + str(self.value) def _eq(self, other: "Leaf") -> bool: """Compare two nodes for equality.""" return (self.type, self.value) == (other.type, other.value) def clone(self) -> "Leaf": assert self.type is not None """Return a cloned (deep) copy of self.""" return Leaf( self.type, self.value, (self.prefix, (self.lineno, self.column)), fixers_applied=self.fixers_applied, ) def leaves(self) -> Iterator["Leaf"]: yield self def post_order(self) -> Iterator["Leaf"]: """Return a post-order iterator for the tree.""" yield self def pre_order(self) -> Iterator["Leaf"]: """Return a pre-order iterator for the tree.""" yield self @property def prefix(self) -> str: """ The whitespace and comments preceding this token in the input. """ return self._prefix @prefix.setter def prefix(self, prefix: str) -> None: self.changed() self._prefix = prefix def convert(gr: Grammar, raw_node: RawNode) -> NL: """ Convert raw node information to a Node or Leaf instance. This is passed to the parser driver which calls it whenever a reduction of a grammar rule produces a new complete node, so that the tree is build strictly bottom-up. """ type, value, context, children = raw_node if children or type in gr.number2symbol: # If there's exactly one child, return that child instead of # creating a new node. assert children is not None if len(children) == 1: return children[0] return Node(type, children, context=context) else: return Leaf(type, value or "", context=context) _Results = dict[str, NL] class BasePattern: """ A pattern is a tree matching pattern. It looks for a specific node type (token or symbol), and optionally for a specific content. This is an abstract base class. There are three concrete subclasses: - LeafPattern matches a single leaf node; - NodePattern matches a single node (usually non-leaf); - WildcardPattern matches a sequence of nodes of variable length. """ # Defaults for instance variables type: int | None type = None # Node type (token if < 256, symbol if >= 256) content: Any = None # Optional content matching pattern name: str | None = None # Optional name used to store match in results dict def __new__(cls, *args, **kwds): """Constructor that prevents BasePattern from being instantiated.""" assert cls is not BasePattern, "Cannot instantiate BasePattern" return object.__new__(cls) def __repr__(self) -> str: assert self.type is not None args = [type_repr(self.type), self.content, self.name] while args and args[-1] is None: del args[-1] return f"{self.__class__.__name__}({', '.join(map(repr, args))})" def _submatch(self, node, results=None) -> bool: raise NotImplementedError def optimize(self) -> "BasePattern": """ A subclass can define this as a hook for optimizations. Returns either self or another node with the same effect. """ return self def match(self, node: NL, results: _Results | None = None) -> bool: """ Does this pattern exactly match a node? Returns True if it matches, False if not. If results is not None, it must be a dict which will be updated with the nodes matching named subpatterns. Default implementation for non-wildcard patterns. """ if self.type is not None and node.type != self.type: return False if self.content is not None: r: _Results | None = None if results is not None: r = {} if not self._submatch(node, r): return False if r: assert results is not None results.update(r) if results is not None and self.name: results[self.name] = node return True def match_seq(self, nodes: list[NL], results: _Results | None = None) -> bool: """ Does this pattern exactly match a sequence of nodes? Default implementation for non-wildcard patterns. """ if len(nodes) != 1: return False return self.match(nodes[0], results) def generate_matches(self, nodes: list[NL]) -> Iterator[tuple[int, _Results]]: """ Generator yielding all matches for this pattern. Default implementation for non-wildcard patterns. """ r: _Results = {} if nodes and self.match(nodes[0], r): yield 1, r class LeafPattern(BasePattern): def __init__( self, type: int | None = None, content: str | None = None, name: str | None = None, ) -> None: """ Initializer. Takes optional type, content, and name. The type, if given must be a token type (< 256). If not given, this matches any *leaf* node; the content may still be required. The content, if given, must be a string. If a name is given, the matching node is stored in the results dict under that key. """ if type is not None: assert 0 <= type < 256, type if content is not None: assert isinstance(content, str), repr(content) self.type = type self.content = content self.name = name def match(self, node: NL, results=None) -> bool: """Override match() to insist on a leaf node.""" if not isinstance(node, Leaf): return False return BasePattern.match(self, node, results) def _submatch(self, node, results=None): """ Match the pattern's content to the node's children. This assumes the node type matches and self.content is not None. Returns True if it matches, False if not. If results is not None, it must be a dict which will be updated with the nodes matching named subpatterns. When returning False, the results dict may still be updated. """ return self.content == node.value class NodePattern(BasePattern): wildcards: bool = False def __init__( self, type: int | None = None, content: Iterable[str] | None = None, name: str | None = None, ) -> None: """ Initializer. Takes optional type, content, and name. The type, if given, must be a symbol type (>= 256). If the type is None this matches *any* single node (leaf or not), except if content is not None, in which it only matches non-leaf nodes that also match the content pattern. The content, if not None, must be a sequence of Patterns that must match the node's children exactly. If the content is given, the type must not be None. If a name is given, the matching node is stored in the results dict under that key. """ if type is not None: assert type >= 256, type if content is not None: assert not isinstance(content, str), repr(content) newcontent = list(content) for i, item in enumerate(newcontent): assert isinstance(item, BasePattern), (i, item) # I don't even think this code is used anywhere, but it does cause # unreachable errors from mypy. This function's signature does look # odd though *shrug*. if isinstance(item, WildcardPattern): # type: ignore[unreachable] self.wildcards = True # type: ignore[unreachable] self.type = type self.content = newcontent # TODO: this is unbound when content is None self.name = name def _submatch(self, node, results=None) -> bool: """ Match the pattern's content to the node's children. This assumes the node type matches and self.content is not None. Returns True if it matches, False if not. If results is not None, it must be a dict which will be updated with the nodes matching named subpatterns. When returning False, the results dict may still be updated. """ if self.wildcards: for c, r in generate_matches(self.content, node.children): if c == len(node.children): if results is not None: results.update(r) return True return False if len(self.content) != len(node.children): return False for subpattern, child in zip(self.content, node.children): if not subpattern.match(child, results): return False return True class WildcardPattern(BasePattern): """ A wildcard pattern can match zero or more nodes. This has all the flexibility needed to implement patterns like: .* .+ .? .{m,n} (a b c | d e | f) (...)* (...)+ (...)? (...){m,n} except it always uses non-greedy matching. """ min: int max: int def __init__( self, content: str | None = None, min: int = 0, max: int = HUGE, name: str | None = None, ) -> None: """ Initializer. Args: content: optional sequence of subsequences of patterns; if absent, matches one node; if present, each subsequence is an alternative [*] min: optional minimum number of times to match, default 0 max: optional maximum number of times to match, default HUGE name: optional name assigned to this match [*] Thus, if content is [[a, b, c], [d, e], [f, g, h]] this is equivalent to (a b c | d e | f g h); if content is None, this is equivalent to '.' in regular expression terms. The min and max parameters work as follows: min=0, max=maxint: .* min=1, max=maxint: .+ min=0, max=1: .? min=1, max=1: . If content is not None, replace the dot with the parenthesized list of alternatives, e.g. (a b c | d e | f g h)* """ assert 0 <= min <= max <= HUGE, (min, max) if content is not None: f = lambda s: tuple(s) wrapped_content = tuple(map(f, content)) # Protect against alterations # Check sanity of alternatives assert len(wrapped_content), repr( wrapped_content ) # Can't have zero alternatives for alt in wrapped_content: assert len(alt), repr(alt) # Can have empty alternatives self.content = wrapped_content self.min = min self.max = max self.name = name def optimize(self) -> Any: """Optimize certain stacked wildcard patterns.""" subpattern = None if ( self.content is not None and len(self.content) == 1 and len(self.content[0]) == 1 ): subpattern = self.content[0][0] if self.min == 1 and self.max == 1: if self.content is None: return NodePattern(name=self.name) if subpattern is not None and self.name == subpattern.name: return subpattern.optimize() if ( self.min <= 1 and isinstance(subpattern, WildcardPattern) and subpattern.min <= 1 and self.name == subpattern.name ): return WildcardPattern( subpattern.content, self.min * subpattern.min, self.max * subpattern.max, subpattern.name, ) return self def match(self, node, results=None) -> bool: """Does this pattern exactly match a node?""" return self.match_seq([node], results) def match_seq(self, nodes, results=None) -> bool: """Does this pattern exactly match a sequence of nodes?""" for c, r in self.generate_matches(nodes): if c == len(nodes): if results is not None: results.update(r) if self.name: results[self.name] = list(nodes) return True return False def generate_matches(self, nodes) -> Iterator[tuple[int, _Results]]: """ Generator yielding matches for a sequence of nodes. Args: nodes: sequence of nodes Yields: (count, results) tuples where: count: the match comprises nodes[:count]; results: dict containing named submatches. """ if self.content is None: # Shortcut for special case (see __init__.__doc__) for count in range(self.min, 1 + min(len(nodes), self.max)): r = {} if self.name: r[self.name] = nodes[:count] yield count, r elif self.name == "bare_name": yield self._bare_name_matches(nodes) else: # The reason for this is that hitting the recursion limit usually # results in some ugly messages about how RuntimeErrors are being # ignored. We only have to do this on CPython, though, because other # implementations don't have this nasty bug in the first place. if hasattr(sys, "getrefcount"): save_stderr = sys.stderr sys.stderr = StringIO() try: for count, r in self._recursive_matches(nodes, 0): if self.name: r[self.name] = nodes[:count] yield count, r except RuntimeError: # We fall back to the iterative pattern matching scheme if the recursive # scheme hits the recursion limit. for count, r in self._iterative_matches(nodes): if self.name: r[self.name] = nodes[:count] yield count, r finally: if hasattr(sys, "getrefcount"): sys.stderr = save_stderr def _iterative_matches(self, nodes) -> Iterator[tuple[int, _Results]]: """Helper to iteratively yield the matches.""" nodelen = len(nodes) if 0 >= self.min: yield 0, {} results = [] # generate matches that use just one alt from self.content for alt in self.content: for c, r in generate_matches(alt, nodes): yield c, r results.append((c, r)) # for each match, iterate down the nodes while results: new_results = [] for c0, r0 in results: # stop if the entire set of nodes has been matched if c0 < nodelen and c0 <= self.max: for alt in self.content: for c1, r1 in generate_matches(alt, nodes[c0:]): if c1 > 0: r = {} r.update(r0) r.update(r1) yield c0 + c1, r new_results.append((c0 + c1, r)) results = new_results def _bare_name_matches(self, nodes) -> tuple[int, _Results]: """Special optimized matcher for bare_name.""" count = 0 r = {} # type: _Results done = False max = len(nodes) while not done and count < max: done = True for leaf in self.content: if leaf[0].match(nodes[count], r): count += 1 done = False break assert self.name is not None r[self.name] = nodes[:count] return count, r def _recursive_matches(self, nodes, count) -> Iterator[tuple[int, _Results]]: """Helper to recursively yield the matches.""" assert self.content is not None if count >= self.min: yield 0, {} if count < self.max: for alt in self.content: for c0, r0 in generate_matches(alt, nodes): for c1, r1 in self._recursive_matches(nodes[c0:], count + 1): r = {} r.update(r0) r.update(r1) yield c0 + c1, r class NegatedPattern(BasePattern): def __init__(self, content: BasePattern | None = None) -> None: """ Initializer. The argument is either a pattern or None. If it is None, this only matches an empty sequence (effectively '$' in regex lingo). If it is not None, this matches whenever the argument pattern doesn't have any matches. """ if content is not None: assert isinstance(content, BasePattern), repr(content) self.content = content def match(self, node, results=None) -> bool: # We never match a node in its entirety return False def match_seq(self, nodes, results=None) -> bool: # We only match an empty sequence of nodes in its entirety return len(nodes) == 0 def generate_matches(self, nodes: list[NL]) -> Iterator[tuple[int, _Results]]: if self.content is None: # Return a match if there is an empty sequence if len(nodes) == 0: yield 0, {} else: # Return a match if the argument pattern has no matches for c, r in self.content.generate_matches(nodes): return yield 0, {} def generate_matches( patterns: list[BasePattern], nodes: list[NL] ) -> Iterator[tuple[int, _Results]]: """ Generator yielding matches for a sequence of patterns and nodes. Args: patterns: a sequence of patterns nodes: a sequence of nodes Yields: (count, results) tuples where: count: the entire sequence of patterns matches nodes[:count]; results: dict containing named submatches. """ if not patterns: yield 0, {} else: p, rest = patterns[0], patterns[1:] for c0, r0 in p.generate_matches(nodes): if not rest: yield c0, r0 else: for c1, r1 in generate_matches(rest, nodes[c0:]): r = {} r.update(r0) r.update(r1) yield c0 + c1, r
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/src/blib2to3/pygram.py
src/blib2to3/pygram.py
# Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Export the Python grammar and symbols.""" # Python imports import os from typing import Union # Local imports from .pgen2 import driver from .pgen2.grammar import Grammar # Moved into initialize because mypyc can't handle __file__ (XXX bug) # # The grammar file # _GRAMMAR_FILE = os.path.join(os.path.dirname(__file__), "Grammar.txt") # _PATTERN_GRAMMAR_FILE = os.path.join(os.path.dirname(__file__), # "PatternGrammar.txt") class Symbols: def __init__(self, grammar: Grammar) -> None: """Initializer. Creates an attribute for each grammar symbol (nonterminal), whose value is the symbol's type (an int >= 256). """ for name, symbol in grammar.symbol2number.items(): setattr(self, name, symbol) class _python_symbols(Symbols): and_expr: int and_test: int annassign: int arglist: int argument: int arith_expr: int asexpr_test: int assert_stmt: int async_funcdef: int async_stmt: int atom: int augassign: int break_stmt: int case_block: int classdef: int comp_for: int comp_if: int comp_iter: int comp_op: int comparison: int compound_stmt: int continue_stmt: int decorated: int decorator: int decorators: int del_stmt: int dictsetmaker: int dotted_as_name: int dotted_as_names: int dotted_name: int encoding_decl: int eval_input: int except_clause: int expr: int expr_stmt: int exprlist: int factor: int file_input: int flow_stmt: int for_stmt: int fstring: int fstring_format_spec: int fstring_middle: int fstring_replacement_field: int funcdef: int global_stmt: int guard: int if_stmt: int import_as_name: int import_as_names: int import_from: int import_name: int import_stmt: int lambdef: int listmaker: int match_stmt: int namedexpr_test: int not_test: int old_comp_for: int old_comp_if: int old_comp_iter: int old_lambdef: int old_test: int or_test: int parameters: int paramspec: int pass_stmt: int pattern: int patterns: int power: int raise_stmt: int return_stmt: int shift_expr: int simple_stmt: int single_input: int sliceop: int small_stmt: int subject_expr: int star_expr: int stmt: int subscript: int subscriptlist: int suite: int term: int test: int testlist: int testlist1: int testlist_gexp: int testlist_safe: int testlist_star_expr: int tfpdef: int tfplist: int tname: int tname_star: int trailer: int try_stmt: int tstring: int tstring_format_spec: int tstring_middle: int tstring_replacement_field: int type_stmt: int typedargslist: int typeparam: int typeparams: int typevar: int typevartuple: int varargslist: int vfpdef: int vfplist: int vname: int while_stmt: int with_stmt: int xor_expr: int yield_arg: int yield_expr: int yield_stmt: int class _pattern_symbols(Symbols): Alternative: int Alternatives: int Details: int Matcher: int NegatedUnit: int Repeater: int Unit: int python_grammar: Grammar python_grammar_async_keywords: Grammar python_grammar_soft_keywords: Grammar pattern_grammar: Grammar python_symbols: _python_symbols pattern_symbols: _pattern_symbols def initialize(cache_dir: Union[str, "os.PathLike[str]", None] = None) -> None: global python_grammar global python_grammar_async_keywords global python_grammar_soft_keywords global python_symbols global pattern_grammar global pattern_symbols # The grammar file _GRAMMAR_FILE = os.path.join(os.path.dirname(__file__), "Grammar.txt") _PATTERN_GRAMMAR_FILE = os.path.join( os.path.dirname(__file__), "PatternGrammar.txt" ) python_grammar = driver.load_packaged_grammar("blib2to3", _GRAMMAR_FILE, cache_dir) assert "print" not in python_grammar.keywords assert "exec" not in python_grammar.keywords soft_keywords = python_grammar.soft_keywords.copy() python_grammar.soft_keywords.clear() python_symbols = _python_symbols(python_grammar) # Python 3.0-3.6 python_grammar.version = (3, 0) # Python 3.7+ python_grammar_async_keywords = python_grammar.copy() python_grammar_async_keywords.async_keywords = True python_grammar_async_keywords.version = (3, 7) # Python 3.10+ python_grammar_soft_keywords = python_grammar_async_keywords.copy() python_grammar_soft_keywords.soft_keywords = soft_keywords python_grammar_soft_keywords.version = (3, 10) pattern_grammar = driver.load_packaged_grammar( "blib2to3", _PATTERN_GRAMMAR_FILE, cache_dir ) pattern_symbols = _pattern_symbols(pattern_grammar)
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/src/blib2to3/__init__.py
src/blib2to3/__init__.py
# empty
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/src/blib2to3/pgen2/conv.py
src/blib2to3/pgen2/conv.py
# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. # mypy: ignore-errors """Convert graminit.[ch] spit out by pgen to Python code. Pgen is the Python parser generator. It is useful to quickly create a parser from a grammar file in Python's grammar notation. But I don't want my parsers to be written in C (yet), so I'm translating the parsing tables to Python data structures and writing a Python parse engine. Note that the token numbers are constants determined by the standard Python tokenizer. The standard token module defines these numbers and their names (the names are not used much). The token numbers are hardcoded into the Python tokenizer and into pgen. A Python implementation of the Python tokenizer is also available, in the standard tokenize module. On the other hand, symbol numbers (representing the grammar's non-terminals) are assigned by pgen based on the actual grammar input. Note: this module is pretty much obsolete; the pgen module generates equivalent grammar tables directly from the Grammar.txt input file without having to invoke the Python pgen C program. """ # Python imports import re # Local imports from blib2to3.pgen2 import grammar, token class Converter(grammar.Grammar): """Grammar subclass that reads classic pgen output files. The run() method reads the tables as produced by the pgen parser generator, typically contained in two C files, graminit.h and graminit.c. The other methods are for internal use only. See the base class for more documentation. """ def run(self, graminit_h, graminit_c): """Load the grammar tables from the text files written by pgen.""" self.parse_graminit_h(graminit_h) self.parse_graminit_c(graminit_c) self.finish_off() def parse_graminit_h(self, filename): """Parse the .h file written by pgen. (Internal) This file is a sequence of #define statements defining the nonterminals of the grammar as numbers. We build two tables mapping the numbers to names and back. """ try: f = open(filename) except OSError as err: print(f"Can't open {filename}: {err}") return False self.symbol2number = {} self.number2symbol = {} lineno = 0 for line in f: lineno += 1 mo = re.match(r"^#define\s+(\w+)\s+(\d+)$", line) if not mo and line.strip(): print(f"{filename}({lineno}): can't parse {line.strip()}") else: symbol, number = mo.groups() number = int(number) assert symbol not in self.symbol2number assert number not in self.number2symbol self.symbol2number[symbol] = number self.number2symbol[number] = symbol return True def parse_graminit_c(self, filename): """Parse the .c file written by pgen. (Internal) The file looks as follows. The first two lines are always this: #include "pgenheaders.h" #include "grammar.h" After that come four blocks: 1) one or more state definitions 2) a table defining dfas 3) a table defining labels 4) a struct defining the grammar A state definition has the following form: - one or more arc arrays, each of the form: static arc arcs_<n>_<m>[<k>] = { {<i>, <j>}, ... }; - followed by a state array, of the form: static state states_<s>[<t>] = { {<k>, arcs_<n>_<m>}, ... }; """ try: f = open(filename) except OSError as err: print(f"Can't open {filename}: {err}") return False # The code below essentially uses f's iterator-ness! lineno = 0 # Expect the two #include lines lineno, line = lineno + 1, next(f) assert line == '#include "pgenheaders.h"\n', (lineno, line) lineno, line = lineno + 1, next(f) assert line == '#include "grammar.h"\n', (lineno, line) # Parse the state definitions lineno, line = lineno + 1, next(f) allarcs = {} states = [] while line.startswith("static arc "): while line.startswith("static arc "): mo = re.match(r"static arc arcs_(\d+)_(\d+)\[(\d+)\] = {$", line) assert mo, (lineno, line) n, m, k = list(map(int, mo.groups())) arcs = [] for _ in range(k): lineno, line = lineno + 1, next(f) mo = re.match(r"\s+{(\d+), (\d+)},$", line) assert mo, (lineno, line) i, j = list(map(int, mo.groups())) arcs.append((i, j)) lineno, line = lineno + 1, next(f) assert line == "};\n", (lineno, line) allarcs[(n, m)] = arcs lineno, line = lineno + 1, next(f) mo = re.match(r"static state states_(\d+)\[(\d+)\] = {$", line) assert mo, (lineno, line) s, t = list(map(int, mo.groups())) assert s == len(states), (lineno, line) state = [] for _ in range(t): lineno, line = lineno + 1, next(f) mo = re.match(r"\s+{(\d+), arcs_(\d+)_(\d+)},$", line) assert mo, (lineno, line) k, n, m = list(map(int, mo.groups())) arcs = allarcs[n, m] assert k == len(arcs), (lineno, line) state.append(arcs) states.append(state) lineno, line = lineno + 1, next(f) assert line == "};\n", (lineno, line) lineno, line = lineno + 1, next(f) self.states = states # Parse the dfas dfas = {} mo = re.match(r"static dfa dfas\[(\d+)\] = {$", line) assert mo, (lineno, line) ndfas = int(mo.group(1)) for i in range(ndfas): lineno, line = lineno + 1, next(f) mo = re.match(r'\s+{(\d+), "(\w+)", (\d+), (\d+), states_(\d+),$', line) assert mo, (lineno, line) symbol = mo.group(2) number, x, y, z = list(map(int, mo.group(1, 3, 4, 5))) assert self.symbol2number[symbol] == number, (lineno, line) assert self.number2symbol[number] == symbol, (lineno, line) assert x == 0, (lineno, line) state = states[z] assert y == len(state), (lineno, line) lineno, line = lineno + 1, next(f) mo = re.match(r'\s+("(?:\\\d\d\d)*")},$', line) assert mo, (lineno, line) first = {} rawbitset = eval(mo.group(1)) for i, c in enumerate(rawbitset): byte = ord(c) for j in range(8): if byte & (1 << j): first[i * 8 + j] = 1 dfas[number] = (state, first) lineno, line = lineno + 1, next(f) assert line == "};\n", (lineno, line) self.dfas = dfas # Parse the labels labels = [] lineno, line = lineno + 1, next(f) mo = re.match(r"static label labels\[(\d+)\] = {$", line) assert mo, (lineno, line) nlabels = int(mo.group(1)) for i in range(nlabels): lineno, line = lineno + 1, next(f) mo = re.match(r'\s+{(\d+), (0|"\w+")},$', line) assert mo, (lineno, line) x, y = mo.groups() x = int(x) if y == "0": y = None else: y = eval(y) labels.append((x, y)) lineno, line = lineno + 1, next(f) assert line == "};\n", (lineno, line) self.labels = labels # Parse the grammar struct lineno, line = lineno + 1, next(f) assert line == "grammar _PyParser_Grammar = {\n", (lineno, line) lineno, line = lineno + 1, next(f) mo = re.match(r"\s+(\d+),$", line) assert mo, (lineno, line) ndfas = int(mo.group(1)) assert ndfas == len(self.dfas) lineno, line = lineno + 1, next(f) assert line == "\tdfas,\n", (lineno, line) lineno, line = lineno + 1, next(f) mo = re.match(r"\s+{(\d+), labels},$", line) assert mo, (lineno, line) nlabels = int(mo.group(1)) assert nlabels == len(self.labels), (lineno, line) lineno, line = lineno + 1, next(f) mo = re.match(r"\s+(\d+)$", line) assert mo, (lineno, line) start = int(mo.group(1)) assert start in self.number2symbol, (lineno, line) self.start = start lineno, line = lineno + 1, next(f) assert line == "};\n", (lineno, line) try: lineno, line = lineno + 1, next(f) except StopIteration: pass else: assert 0, (lineno, line) def finish_off(self): """Create additional useful structures. (Internal).""" self.keywords = {} # map from keyword strings to arc labels self.tokens = {} # map from numeric token values to arc labels for ilabel, (type, value) in enumerate(self.labels): if type == token.NAME and value is not None: self.keywords[value] = ilabel elif value is None: self.tokens[type] = ilabel
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/src/blib2to3/pgen2/literals.py
src/blib2to3/pgen2/literals.py
# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Safely evaluate Python string literals without using eval().""" import re simple_escapes: dict[str, str] = { "a": "\a", "b": "\b", "f": "\f", "n": "\n", "r": "\r", "t": "\t", "v": "\v", "'": "'", '"': '"', "\\": "\\", } def escape(m: re.Match[str]) -> str: all, tail = m.group(0, 1) assert all.startswith("\\") esc = simple_escapes.get(tail) if esc is not None: return esc if tail.startswith("x"): hexes = tail[1:] if len(hexes) < 2: raise ValueError(f"invalid hex string escape ('\\{tail}')") try: i = int(hexes, 16) except ValueError: raise ValueError(f"invalid hex string escape ('\\{tail}')") from None else: try: i = int(tail, 8) except ValueError: raise ValueError(f"invalid octal string escape ('\\{tail}')") from None return chr(i) def evalString(s: str) -> str: assert s.startswith("'") or s.startswith('"'), repr(s[:1]) q = s[0] if s[:3] == q * 3: q = q * 3 assert s.endswith(q), repr(s[-len(q) :]) assert len(s) >= 2 * len(q) s = s[len(q) : -len(q)] return re.sub(r"\\(\'|\"|\\|[abfnrtv]|x.{0,2}|[0-7]{1,3})", escape, s) def test() -> None: for i in range(256): c = chr(i) s = repr(c) e = evalString(s) if e != c: print(i, c, s, e) if __name__ == "__main__": test()
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/src/blib2to3/pgen2/driver.py
src/blib2to3/pgen2/driver.py
# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. # Modifications: # Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Parser driver. This provides a high-level interface to parse a file into a syntax tree. """ __author__ = "Guido van Rossum <guido@python.org>" __all__ = ["Driver", "load_grammar"] # Python imports import io import logging import os import pkgutil import sys from collections.abc import Iterable, Iterator from contextlib import contextmanager from dataclasses import dataclass, field from logging import Logger from typing import Any, Union, cast from blib2to3.pgen2.grammar import Grammar from blib2to3.pgen2.tokenize import TokenInfo from blib2to3.pytree import NL # Pgen imports from . import grammar, parse, pgen, token, tokenize Path = Union[str, "os.PathLike[str]"] @dataclass class ReleaseRange: start: int end: int | None = None tokens: list[Any] = field(default_factory=list) def lock(self) -> None: total_eaten = len(self.tokens) self.end = self.start + total_eaten class TokenProxy: def __init__(self, generator: Any) -> None: self._tokens = generator self._counter = 0 self._release_ranges: list[ReleaseRange] = [] @contextmanager def release(self) -> Iterator["TokenProxy"]: release_range = ReleaseRange(self._counter) self._release_ranges.append(release_range) try: yield self finally: # Lock the last release range to the final position that # has been eaten. release_range.lock() def eat(self, point: int) -> Any: eaten_tokens = self._release_ranges[-1].tokens if point < len(eaten_tokens): return eaten_tokens[point] else: while point >= len(eaten_tokens): token = next(self._tokens) eaten_tokens.append(token) return token def __iter__(self) -> "TokenProxy": return self def __next__(self) -> Any: # If the current position is already compromised (looked up) # return the eaten token, if not just go further on the given # token producer. for release_range in self._release_ranges: assert release_range.end is not None start, end = release_range.start, release_range.end if start <= self._counter < end: token = release_range.tokens[self._counter - start] break else: token = next(self._tokens) self._counter += 1 return token def can_advance(self, to: int) -> bool: # Try to eat, fail if it can't. The eat operation is cached # so there won't be any additional cost of eating here try: self.eat(to) except StopIteration: return False else: return True class Driver: def __init__(self, grammar: Grammar, logger: Logger | None = None) -> None: self.grammar = grammar if logger is None: logger = logging.getLogger(__name__) self.logger = logger def parse_tokens(self, tokens: Iterable[TokenInfo], debug: bool = False) -> NL: """Parse a series of tokens and return the syntax tree.""" # XXX Move the prefix computation into a wrapper around tokenize. proxy = TokenProxy(tokens) p = parse.Parser(self.grammar) p.setup(proxy=proxy) lineno = 1 column = 0 indent_columns: list[int] = [] type = value = start = end = line_text = None prefix = "" for quintuple in proxy: type, value, start, end, line_text = quintuple if start != (lineno, column): assert (lineno, column) <= start, ((lineno, column), start) s_lineno, s_column = start if lineno < s_lineno: prefix += "\n" * (s_lineno - lineno) lineno = s_lineno column = 0 if column < s_column: prefix += line_text[column:s_column] column = s_column if type in (tokenize.COMMENT, tokenize.NL): prefix += value lineno, column = end if value.endswith("\n"): lineno += 1 column = 0 continue if type == token.OP: type = grammar.opmap[value] if debug: assert type is not None self.logger.debug( "%s %r (prefix=%r)", token.tok_name[type], value, prefix ) if type == token.INDENT: indent_columns.append(len(value)) _prefix = prefix + value prefix = "" value = "" elif type == token.DEDENT: _indent_col = indent_columns.pop() prefix, _prefix = self._partially_consume_prefix(prefix, _indent_col) if p.addtoken(cast(int, type), value, (prefix, start)): if debug: self.logger.debug("Stop.") break prefix = "" if type in {token.INDENT, token.DEDENT}: prefix = _prefix lineno, column = end # FSTRING_MIDDLE and TSTRING_MIDDLE are the only token that can end with a # newline, and `end` will point to the next line. For that case, don't # increment lineno. if value.endswith("\n") and type not in ( token.FSTRING_MIDDLE, token.TSTRING_MIDDLE, ): lineno += 1 column = 0 else: # We never broke out -- EOF is too soon (how can this happen???) assert start is not None raise parse.ParseError("incomplete input", type, value, (prefix, start)) assert p.rootnode is not None return p.rootnode def parse_file( self, filename: Path, encoding: str | None = None, debug: bool = False ) -> NL: """Parse a file and return the syntax tree.""" with open(filename, encoding=encoding) as stream: text = stream.read() return self.parse_string(text, debug) def parse_string(self, text: str, debug: bool = False) -> NL: """Parse a string and return the syntax tree.""" tokens = tokenize.tokenize(text, grammar=self.grammar) return self.parse_tokens(tokens, debug) def _partially_consume_prefix(self, prefix: str, column: int) -> tuple[str, str]: lines: list[str] = [] current_line = "" current_column = 0 wait_for_nl = False for char in prefix: current_line += char if wait_for_nl: if char == "\n": if current_line.strip() and current_column < column: res = "".join(lines) return res, prefix[len(res) :] lines.append(current_line) current_line = "" current_column = 0 wait_for_nl = False elif char in " \t": current_column += 1 elif char == "\n": # unexpected empty line current_column = 0 elif char == "\f": current_column = 0 else: # indent is finished wait_for_nl = True return "".join(lines), current_line def _generate_pickle_name(gt: Path, cache_dir: Path | None = None) -> str: head, tail = os.path.splitext(gt) if tail == ".txt": tail = "" name = head + tail + ".".join(map(str, sys.version_info)) + ".pickle" if cache_dir: return os.path.join(cache_dir, os.path.basename(name)) else: return name def load_grammar( gt: str = "Grammar.txt", gp: str | None = None, save: bool = True, force: bool = False, logger: Logger | None = None, ) -> Grammar: """Load the grammar (maybe from a pickle).""" if logger is None: logger = logging.getLogger(__name__) gp = _generate_pickle_name(gt) if gp is None else gp if force or not _newer(gp, gt): g: grammar.Grammar = pgen.generate_grammar(gt) if save: try: g.dump(gp) except OSError: # Ignore error, caching is not vital. pass else: g = grammar.Grammar() g.load(gp) return g def _newer(a: str, b: str) -> bool: """Inquire whether file a was written since file b.""" if not os.path.exists(a): return False if not os.path.exists(b): return True return os.path.getmtime(a) >= os.path.getmtime(b) def load_packaged_grammar( package: str, grammar_source: str, cache_dir: Path | None = None ) -> grammar.Grammar: """Normally, loads a pickled grammar by doing pkgutil.get_data(package, pickled_grammar) where *pickled_grammar* is computed from *grammar_source* by adding the Python version and using a ``.pickle`` extension. However, if *grammar_source* is an extant file, load_grammar(grammar_source) is called instead. This facilitates using a packaged grammar file when needed but preserves load_grammar's automatic regeneration behavior when possible. """ if os.path.isfile(grammar_source): gp = _generate_pickle_name(grammar_source, cache_dir) if cache_dir else None return load_grammar(grammar_source, gp=gp) pickled_name = _generate_pickle_name(os.path.basename(grammar_source), cache_dir) data = pkgutil.get_data(package, pickled_name) assert data is not None g = grammar.Grammar() g.loads(data) return g def main(*args: str) -> bool: """Main program, when run as a script: produce grammar pickle files. Calls load_grammar for each argument, a path to a grammar text file. """ if not args: args = tuple(sys.argv[1:]) logging.basicConfig(level=logging.INFO, stream=sys.stdout, format="%(message)s") for gt in args: load_grammar(gt, save=True, force=True) return True if __name__ == "__main__": sys.exit(int(not main()))
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/src/blib2to3/pgen2/token.py
src/blib2to3/pgen2/token.py
"""Token constants (from "token.h").""" from typing import Final # Taken from Python (r53757) and modified to include some tokens # originally monkeypatched in by pgen2.tokenize # --start constants-- ENDMARKER: Final = 0 NAME: Final = 1 NUMBER: Final = 2 STRING: Final = 3 NEWLINE: Final = 4 INDENT: Final = 5 DEDENT: Final = 6 LPAR: Final = 7 RPAR: Final = 8 LSQB: Final = 9 RSQB: Final = 10 COLON: Final = 11 COMMA: Final = 12 SEMI: Final = 13 PLUS: Final = 14 MINUS: Final = 15 STAR: Final = 16 SLASH: Final = 17 VBAR: Final = 18 AMPER: Final = 19 LESS: Final = 20 GREATER: Final = 21 EQUAL: Final = 22 DOT: Final = 23 PERCENT: Final = 24 BACKQUOTE: Final = 25 LBRACE: Final = 26 RBRACE: Final = 27 EQEQUAL: Final = 28 NOTEQUAL: Final = 29 LESSEQUAL: Final = 30 GREATEREQUAL: Final = 31 TILDE: Final = 32 CIRCUMFLEX: Final = 33 LEFTSHIFT: Final = 34 RIGHTSHIFT: Final = 35 DOUBLESTAR: Final = 36 PLUSEQUAL: Final = 37 MINEQUAL: Final = 38 STAREQUAL: Final = 39 SLASHEQUAL: Final = 40 PERCENTEQUAL: Final = 41 AMPEREQUAL: Final = 42 VBAREQUAL: Final = 43 CIRCUMFLEXEQUAL: Final = 44 LEFTSHIFTEQUAL: Final = 45 RIGHTSHIFTEQUAL: Final = 46 DOUBLESTAREQUAL: Final = 47 DOUBLESLASH: Final = 48 DOUBLESLASHEQUAL: Final = 49 AT: Final = 50 ATEQUAL: Final = 51 OP: Final = 52 COMMENT: Final = 53 NL: Final = 54 RARROW: Final = 55 AWAIT: Final = 56 ASYNC: Final = 57 ERRORTOKEN: Final = 58 COLONEQUAL: Final = 59 FSTRING_START: Final = 60 FSTRING_MIDDLE: Final = 61 FSTRING_END: Final = 62 BANG: Final = 63 TSTRING_START: Final = 64 TSTRING_MIDDLE: Final = 65 TSTRING_END: Final = 66 N_TOKENS: Final = 67 NT_OFFSET: Final = 256 # --end constants-- tok_name: Final[dict[int, str]] = {} for _name, _value in list(globals().items()): if type(_value) is int: tok_name[_value] = _name def ISTERMINAL(x: int) -> bool: return x < NT_OFFSET def ISNONTERMINAL(x: int) -> bool: return x >= NT_OFFSET def ISEOF(x: int) -> bool: return x == ENDMARKER
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/src/blib2to3/pgen2/tokenize.py
src/blib2to3/pgen2/tokenize.py
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006 Python Software Foundation. # All rights reserved. # mypy: allow-untyped-defs, allow-untyped-calls """Tokenization help for Python programs. generate_tokens(readline) is a generator that breaks a stream of text into Python tokens. It accepts a readline-like method which is called repeatedly to get the next line of input (or "" for EOF). It generates 5-tuples with these members: the token type (see token.py) the token (a string) the starting (row, column) indices of the token (a 2-tuple of ints) the ending (row, column) indices of the token (a 2-tuple of ints) the original line (string) It is designed to match the working of the Python tokenizer exactly, except that it produces COMMENT tokens for comments and gives type OP for all operators Older entry points tokenize_loop(readline, tokeneater) tokenize(readline, tokeneater=printtoken) are the same, except instead of generating tokens, tokeneater is a callback function to which the 5 fields described above are passed as 5 arguments, each time a new token is found.""" import sys from collections.abc import Iterator from blib2to3.pgen2.grammar import Grammar from blib2to3.pgen2.token import ( ASYNC, AWAIT, COMMENT, DEDENT, ENDMARKER, FSTRING_END, FSTRING_MIDDLE, FSTRING_START, INDENT, NAME, NEWLINE, NL, NUMBER, OP, STRING, TSTRING_END, TSTRING_MIDDLE, TSTRING_START, tok_name, ) __author__ = "Ka-Ping Yee <ping@lfw.org>" __credits__ = "GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, Skip Montanaro" import pytokens from pytokens import TokenType from . import token as _token __all__ = [x for x in dir(_token) if x[0] != "_"] + [ "tokenize", "generate_tokens", "untokenize", ] del _token Coord = tuple[int, int] TokenInfo = tuple[int, str, Coord, Coord, str] TOKEN_TYPE_MAP = { TokenType.indent: INDENT, TokenType.dedent: DEDENT, TokenType.newline: NEWLINE, TokenType.nl: NL, TokenType.comment: COMMENT, TokenType.semicolon: OP, TokenType.lparen: OP, TokenType.rparen: OP, TokenType.lbracket: OP, TokenType.rbracket: OP, TokenType.lbrace: OP, TokenType.rbrace: OP, TokenType.colon: OP, TokenType.op: OP, TokenType.identifier: NAME, TokenType.number: NUMBER, TokenType.string: STRING, TokenType.fstring_start: FSTRING_START, TokenType.fstring_middle: FSTRING_MIDDLE, TokenType.fstring_end: FSTRING_END, TokenType.tstring_start: TSTRING_START, TokenType.tstring_middle: TSTRING_MIDDLE, TokenType.tstring_end: TSTRING_END, TokenType.endmarker: ENDMARKER, } class TokenError(Exception): ... def transform_whitespace( token: pytokens.Token, source: str, prev_token: pytokens.Token | None ) -> pytokens.Token: r""" Black treats `\\\n` at the end of a line as a 'NL' token, while it is ignored as whitespace in the regular Python parser. But, only the first one. If there's a `\\\n` following it (as in, a \ just by itself on a line), that is not made into NL. """ if ( token.type == TokenType.whitespace and prev_token is not None and prev_token.type not in (TokenType.nl, TokenType.newline) ): token_str = source[token.start_index : token.end_index] if token_str.startswith("\\\r\n"): return pytokens.Token( TokenType.nl, token.start_index, token.start_index + 3, token.start_line, token.start_col, token.start_line, token.start_col + 3, ) elif token_str.startswith("\\\n") or token_str.startswith("\\\r"): return pytokens.Token( TokenType.nl, token.start_index, token.start_index + 2, token.start_line, token.start_col, token.start_line, token.start_col + 2, ) return token def tokenize(source: str, grammar: Grammar | None = None) -> Iterator[TokenInfo]: lines = source.split("\n") lines += [""] # For newline tokens in files that don't end in a newline line, column = 1, 0 prev_token: pytokens.Token | None = None try: for token in pytokens.tokenize(source): token = transform_whitespace(token, source, prev_token) line, column = token.start_line, token.start_col if token.type == TokenType.whitespace: continue token_str = source[token.start_index : token.end_index] if token.type == TokenType.newline and token_str == "": # Black doesn't yield empty newline tokens at the end of a file # if there's no newline at the end of a file. prev_token = token continue source_line = lines[token.start_line - 1] if token.type == TokenType.identifier and token_str in ("async", "await"): # Black uses `async` and `await` token types just for those two keywords yield ( ASYNC if token_str == "async" else AWAIT, token_str, (token.start_line, token.start_col), (token.end_line, token.end_col), source_line, ) elif token.type == TokenType.op and token_str == "...": # Black doesn't have an ellipsis token yet, yield 3 DOTs instead assert token.start_line == token.end_line assert token.end_col == token.start_col + 3 token_str = "." for start_col in range(token.start_col, token.start_col + 3): end_col = start_col + 1 yield ( TOKEN_TYPE_MAP[token.type], token_str, (token.start_line, start_col), (token.end_line, end_col), source_line, ) else: token_type = TOKEN_TYPE_MAP.get(token.type) if token_type is None: raise ValueError(f"Unknown token type: {token.type!r}") yield ( TOKEN_TYPE_MAP[token.type], token_str, (token.start_line, token.start_col), (token.end_line, token.end_col), source_line, ) prev_token = token except pytokens.UnexpectedEOF: raise TokenError("Unexpected EOF in multi-line statement", (line, column)) except pytokens.TokenizeError as exc: raise TokenError(f"Failed to parse: {type(exc).__name__}", (line, column)) def printtoken( type: int, token: str, srow_col: Coord, erow_col: Coord, line: str ) -> None: # for testing srow, scol = srow_col erow, ecol = erow_col print(f"{srow},{scol}-{erow},{ecol}:\t{tok_name[type]}\t{token!r}") if __name__ == "__main__": # testing if len(sys.argv) > 1: token_iterator = tokenize(open(sys.argv[1]).read()) else: token_iterator = tokenize(sys.stdin.read()) for tok in token_iterator: printtoken(*tok)
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/src/blib2to3/pgen2/parse.py
src/blib2to3/pgen2/parse.py
# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Parser engine for the grammar tables generated by pgen. The grammar table must be loaded first. See Parser/parser.c in the Python distribution for additional info on how this parsing engine works. """ from collections.abc import Callable, Iterator from contextlib import contextmanager from typing import TYPE_CHECKING, Union, cast from blib2to3.pgen2.grammar import Grammar from blib2to3.pytree import NL, Context, Leaf, Node, RawNode, convert # Local imports from . import grammar, token, tokenize if TYPE_CHECKING: from blib2to3.pgen2.driver import TokenProxy Results = dict[str, NL] Convert = Callable[[Grammar, RawNode], Union[Node, Leaf]] DFA = list[list[tuple[int, int]]] DFAS = tuple[DFA, dict[int, int]] def lam_sub(grammar: Grammar, node: RawNode) -> NL: assert node[3] is not None return Node(type=node[0], children=node[3], context=node[2]) # A placeholder node, used when parser is backtracking. DUMMY_NODE = (-1, None, None, None) def stack_copy( stack: list[tuple[DFAS, int, RawNode]], ) -> list[tuple[DFAS, int, RawNode]]: """Nodeless stack copy.""" return [(dfa, label, DUMMY_NODE) for dfa, label, _ in stack] class Recorder: def __init__(self, parser: "Parser", ilabels: list[int], context: Context) -> None: self.parser = parser self._ilabels = ilabels self.context = context # not really matter self._dead_ilabels: set[int] = set() self._start_point = self.parser.stack self._points = {ilabel: stack_copy(self._start_point) for ilabel in ilabels} @property def ilabels(self) -> set[int]: return self._dead_ilabels.symmetric_difference(self._ilabels) @contextmanager def switch_to(self, ilabel: int) -> Iterator[None]: with self.backtrack(): self.parser.stack = self._points[ilabel] try: yield except ParseError: self._dead_ilabels.add(ilabel) finally: self.parser.stack = self._start_point @contextmanager def backtrack(self) -> Iterator[None]: """ Use the node-level invariant ones for basic parsing operations (push/pop/shift). These still will operate on the stack; but they won't create any new nodes, or modify the contents of any other existing nodes. This saves us a ton of time when we are backtracking, since we want to restore to the initial state as quick as possible, which can only be done by having as little mutatations as possible. """ is_backtracking = self.parser.is_backtracking try: self.parser.is_backtracking = True yield finally: self.parser.is_backtracking = is_backtracking def add_token(self, tok_type: int, tok_val: str, raw: bool = False) -> None: for ilabel in self.ilabels: with self.switch_to(ilabel): if raw: self.parser._addtoken(ilabel, tok_type, tok_val, self.context) else: self.parser.addtoken(tok_type, tok_val, self.context) def determine_route( self, value: str | None = None, force: bool = False ) -> int | None: alive_ilabels = self.ilabels if len(alive_ilabels) == 0: *_, most_successful_ilabel = self._dead_ilabels raise ParseError("bad input", most_successful_ilabel, value, self.context) ilabel, *rest = alive_ilabels if force or not rest: return ilabel else: return None class ParseError(Exception): """Exception to signal the parser is stuck.""" def __init__( self, msg: str, type: int | None, value: str | None, context: Context ) -> None: Exception.__init__( self, f"{msg}: type={type!r}, value={value!r}, context={context!r}" ) self.msg = msg self.type = type self.value = value self.context = context class Parser: """Parser engine. The proper usage sequence is: p = Parser(grammar, [converter]) # create instance p.setup([start]) # prepare for parsing <for each input token>: if p.addtoken(...): # parse a token; may raise ParseError break root = p.rootnode # root of abstract syntax tree A Parser instance may be reused by calling setup() repeatedly. A Parser instance contains state pertaining to the current token sequence, and should not be used concurrently by different threads to parse separate token sequences. See driver.py for how to get input tokens by tokenizing a file or string. Parsing is complete when addtoken() returns True; the root of the abstract syntax tree can then be retrieved from the rootnode instance variable. When a syntax error occurs, addtoken() raises the ParseError exception. There is no error recovery; the parser cannot be used after a syntax error was reported (but it can be reinitialized by calling setup()). """ def __init__(self, grammar: Grammar, convert: Convert | None = None) -> None: """Constructor. The grammar argument is a grammar.Grammar instance; see the grammar module for more information. The parser is not ready yet for parsing; you must call the setup() method to get it started. The optional convert argument is a function mapping concrete syntax tree nodes to abstract syntax tree nodes. If not given, no conversion is done and the syntax tree produced is the concrete syntax tree. If given, it must be a function of two arguments, the first being the grammar (a grammar.Grammar instance), and the second being the concrete syntax tree node to be converted. The syntax tree is converted from the bottom up. **post-note: the convert argument is ignored since for Black's usage, convert will always be blib2to3.pytree.convert. Allowing this to be dynamic hurts mypyc's ability to use early binding. These docs are left for historical and informational value. A concrete syntax tree node is a (type, value, context, nodes) tuple, where type is the node type (a token or symbol number), value is None for symbols and a string for tokens, context is None or an opaque value used for error reporting (typically a (lineno, offset) pair), and nodes is a list of children for symbols, and None for tokens. An abstract syntax tree node may be anything; this is entirely up to the converter function. """ self.grammar = grammar # See note in docstring above. TL;DR this is ignored. self.convert = convert or lam_sub self.is_backtracking = False self.last_token: int | None = None def setup(self, proxy: "TokenProxy", start: int | None = None) -> None: """Prepare for parsing. This *must* be called before starting to parse. The optional argument is an alternative start symbol; it defaults to the grammar's start symbol. You can use a Parser instance to parse any number of programs; each time you call setup() the parser is reset to an initial state determined by the (implicit or explicit) start symbol. """ if start is None: start = self.grammar.start # Each stack entry is a tuple: (dfa, state, node). # A node is a tuple: (type, value, context, children), # where children is a list of nodes or None, and context may be None. newnode: RawNode = (start, None, None, []) stackentry = (self.grammar.dfas[start], 0, newnode) self.stack: list[tuple[DFAS, int, RawNode]] = [stackentry] self.rootnode: NL | None = None self.used_names: set[str] = set() self.proxy = proxy self.last_token = None def addtoken(self, type: int, value: str, context: Context) -> bool: """Add a token; return True iff this is the end of the program.""" # Map from token to label ilabels = self.classify(type, value, context) assert len(ilabels) >= 1 # If we have only one state to advance, we'll directly # take it as is. if len(ilabels) == 1: [ilabel] = ilabels return self._addtoken(ilabel, type, value, context) # If there are multiple states which we can advance (only # happen under soft-keywords), then we will try all of them # in parallel and as soon as one state can reach further than # the rest, we'll choose that one. This is a pretty hacky # and hopefully temporary algorithm. # # For a more detailed explanation, check out this post: # https://tree.science/what-the-backtracking.html with self.proxy.release() as proxy: counter, force = 0, False recorder = Recorder(self, ilabels, context) recorder.add_token(type, value, raw=True) next_token_value = value while recorder.determine_route(next_token_value) is None: if not proxy.can_advance(counter): force = True break next_token_type, next_token_value, *_ = proxy.eat(counter) if next_token_type in (tokenize.COMMENT, tokenize.NL): counter += 1 continue if next_token_type == tokenize.OP: next_token_type = grammar.opmap[next_token_value] recorder.add_token(next_token_type, next_token_value) counter += 1 ilabel = cast(int, recorder.determine_route(next_token_value, force=force)) assert ilabel is not None return self._addtoken(ilabel, type, value, context) def _addtoken(self, ilabel: int, type: int, value: str, context: Context) -> bool: # Loop until the token is shifted; may raise exceptions while True: dfa, state, node = self.stack[-1] states, first = dfa arcs = states[state] # Look for a state with this label for i, newstate in arcs: t = self.grammar.labels[i][0] if t >= 256: # See if it's a symbol and if we're in its first set itsdfa = self.grammar.dfas[t] itsstates, itsfirst = itsdfa if ilabel in itsfirst: # Push a symbol self.push(t, itsdfa, newstate, context) break # To continue the outer while loop elif ilabel == i: # Look it up in the list of labels # Shift a token; we're done with it self.shift(type, value, newstate, context) # Pop while we are in an accept-only state state = newstate while states[state] == [(0, state)]: self.pop() if not self.stack: # Done parsing! return True dfa, state, node = self.stack[-1] states, first = dfa # Done with this token self.last_token = type return False else: if (0, state) in arcs: # An accepting state, pop it and try something else self.pop() if not self.stack: # Done parsing, but another token is input raise ParseError("too much input", type, value, context) else: # No success finding a transition raise ParseError("bad input", type, value, context) def classify(self, type: int, value: str, context: Context) -> list[int]: """Turn a token into a label. (Internal) Depending on whether the value is a soft-keyword or not, this function may return multiple labels to choose from.""" if type == token.NAME: # Keep a listing of all used names self.used_names.add(value) # Check for reserved words if value in self.grammar.keywords: return [self.grammar.keywords[value]] elif value in self.grammar.soft_keywords: assert type in self.grammar.tokens # Current soft keywords (match, case, type) can only appear at the # beginning of a statement. So as a shortcut, don't try to treat them # like keywords in any other context. # ('_' is also a soft keyword in the real grammar, but for our grammar # it's just an expression, so we don't need to treat it specially.) if self.last_token not in ( None, token.INDENT, token.DEDENT, token.NEWLINE, token.SEMI, token.COLON, ): return [self.grammar.tokens[type]] return [ self.grammar.tokens[type], self.grammar.soft_keywords[value], ] ilabel = self.grammar.tokens.get(type) if ilabel is None: raise ParseError("bad token", type, value, context) return [ilabel] def shift(self, type: int, value: str, newstate: int, context: Context) -> None: """Shift a token. (Internal)""" if self.is_backtracking: dfa, state, _ = self.stack[-1] self.stack[-1] = (dfa, newstate, DUMMY_NODE) else: dfa, state, node = self.stack[-1] rawnode: RawNode = (type, value, context, None) newnode = convert(self.grammar, rawnode) assert node[-1] is not None node[-1].append(newnode) self.stack[-1] = (dfa, newstate, node) def push(self, type: int, newdfa: DFAS, newstate: int, context: Context) -> None: """Push a nonterminal. (Internal)""" if self.is_backtracking: dfa, state, _ = self.stack[-1] self.stack[-1] = (dfa, newstate, DUMMY_NODE) self.stack.append((newdfa, 0, DUMMY_NODE)) else: dfa, state, node = self.stack[-1] newnode: RawNode = (type, None, context, []) self.stack[-1] = (dfa, newstate, node) self.stack.append((newdfa, 0, newnode)) def pop(self) -> None: """Pop a nonterminal. (Internal)""" if self.is_backtracking: self.stack.pop() else: popdfa, popstate, popnode = self.stack.pop() newnode = convert(self.grammar, popnode) if self.stack: dfa, state, node = self.stack[-1] assert node[-1] is not None node[-1].append(newnode) else: self.rootnode = newnode self.rootnode.used_names = self.used_names
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/src/blib2to3/pgen2/pgen.py
src/blib2to3/pgen2/pgen.py
# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. import os from collections.abc import Iterator, Sequence from typing import IO, Any, NoReturn, Union from blib2to3.pgen2 import grammar, token, tokenize from blib2to3.pgen2.tokenize import TokenInfo Path = Union[str, "os.PathLike[str]"] class PgenGrammar(grammar.Grammar): pass class ParserGenerator: filename: Path stream: IO[str] generator: Iterator[TokenInfo] first: dict[str, dict[str, int] | None] def __init__(self, filename: Path, stream: IO[str] | None = None) -> None: close_stream = None if stream is None: stream = open(filename, encoding="utf-8") close_stream = stream.close self.filename = filename self.generator = tokenize.tokenize(stream.read()) self.gettoken() # Initialize lookahead self.dfas, self.startsymbol = self.parse() if close_stream is not None: close_stream() self.first = {} # map from symbol name to set of tokens self.addfirstsets() def make_grammar(self) -> PgenGrammar: c = PgenGrammar() names = list(self.dfas.keys()) names.sort() names.remove(self.startsymbol) names.insert(0, self.startsymbol) for name in names: i = 256 + len(c.symbol2number) c.symbol2number[name] = i c.number2symbol[i] = name for name in names: dfa = self.dfas[name] states = [] for state in dfa: arcs = [] for label, next in sorted(state.arcs.items()): arcs.append((self.make_label(c, label), dfa.index(next))) if state.isfinal: arcs.append((0, dfa.index(state))) states.append(arcs) c.states.append(states) c.dfas[c.symbol2number[name]] = (states, self.make_first(c, name)) c.start = c.symbol2number[self.startsymbol] return c def make_first(self, c: PgenGrammar, name: str) -> dict[int, int]: rawfirst = self.first[name] assert rawfirst is not None first = {} for label in sorted(rawfirst): ilabel = self.make_label(c, label) ##assert ilabel not in first # XXX failed on <> ... != first[ilabel] = 1 return first def make_label(self, c: PgenGrammar, label: str) -> int: # XXX Maybe this should be a method on a subclass of converter? ilabel = len(c.labels) if label[0].isalpha(): # Either a symbol name or a named token if label in c.symbol2number: # A symbol name (a non-terminal) if label in c.symbol2label: return c.symbol2label[label] else: c.labels.append((c.symbol2number[label], None)) c.symbol2label[label] = ilabel return ilabel else: # A named token (NAME, NUMBER, STRING) itoken = getattr(token, label, None) assert isinstance(itoken, int), label assert itoken in token.tok_name, label if itoken in c.tokens: return c.tokens[itoken] else: c.labels.append((itoken, None)) c.tokens[itoken] = ilabel return ilabel else: # Either a keyword or an operator assert label[0] in ('"', "'"), label value = eval(label) if value[0].isalpha(): if label[0] == '"': keywords = c.soft_keywords else: keywords = c.keywords # A keyword if value in keywords: return keywords[value] else: c.labels.append((token.NAME, value)) keywords[value] = ilabel return ilabel else: # An operator (any non-numeric token) itoken = grammar.opmap[value] # Fails if unknown token if itoken in c.tokens: return c.tokens[itoken] else: c.labels.append((itoken, None)) c.tokens[itoken] = ilabel return ilabel def addfirstsets(self) -> None: names = list(self.dfas.keys()) names.sort() for name in names: if name not in self.first: self.calcfirst(name) # print name, self.first[name].keys() def calcfirst(self, name: str) -> None: dfa = self.dfas[name] self.first[name] = None # dummy to detect left recursion state = dfa[0] totalset: dict[str, int] = {} overlapcheck = {} for label in state.arcs: if label in self.dfas: if label in self.first: fset = self.first[label] if fset is None: raise ValueError(f"recursion for rule {name!r}") else: self.calcfirst(label) fset = self.first[label] assert fset is not None totalset.update(fset) overlapcheck[label] = fset else: totalset[label] = 1 overlapcheck[label] = {label: 1} inverse: dict[str, str] = {} for label, itsfirst in overlapcheck.items(): for symbol in itsfirst: if symbol in inverse: raise ValueError( f"rule {name} is ambiguous; {symbol} is in the first sets of" f" {label} as well as {inverse[symbol]}" ) inverse[symbol] = label self.first[name] = totalset def parse(self) -> tuple[dict[str, list["DFAState"]], str]: dfas = {} startsymbol: str | None = None # MSTART: (NEWLINE | RULE)* ENDMARKER while self.type != token.ENDMARKER: while self.type == token.NEWLINE: self.gettoken() # RULE: NAME ':' RHS NEWLINE name = self.expect(token.NAME) self.expect(token.OP, ":") a, z = self.parse_rhs() self.expect(token.NEWLINE) # self.dump_nfa(name, a, z) dfa = self.make_dfa(a, z) # self.dump_dfa(name, dfa) # oldlen = len(dfa) self.simplify_dfa(dfa) # newlen = len(dfa) dfas[name] = dfa # print name, oldlen, newlen if startsymbol is None: startsymbol = name assert startsymbol is not None return dfas, startsymbol def make_dfa(self, start: "NFAState", finish: "NFAState") -> list["DFAState"]: # To turn an NFA into a DFA, we define the states of the DFA # to correspond to *sets* of states of the NFA. Then do some # state reduction. Let's represent sets as dicts with 1 for # values. assert isinstance(start, NFAState) assert isinstance(finish, NFAState) def closure(state: NFAState) -> dict[NFAState, int]: base: dict[NFAState, int] = {} addclosure(state, base) return base def addclosure(state: NFAState, base: dict[NFAState, int]) -> None: assert isinstance(state, NFAState) if state in base: return base[state] = 1 for label, next in state.arcs: if label is None: addclosure(next, base) states = [DFAState(closure(start), finish)] for state in states: # NB states grows while we're iterating arcs: dict[str, dict[NFAState, int]] = {} for nfastate in state.nfaset: for label, next in nfastate.arcs: if label is not None: addclosure(next, arcs.setdefault(label, {})) for label, nfaset in sorted(arcs.items()): for st in states: if st.nfaset == nfaset: break else: st = DFAState(nfaset, finish) states.append(st) state.addarc(st, label) return states # List of DFAState instances; first one is start def dump_nfa(self, name: str, start: "NFAState", finish: "NFAState") -> None: print("Dump of NFA for", name) todo = [start] for i, state in enumerate(todo): print(" State", i, state is finish and "(final)" or "") for label, next in state.arcs: if next in todo: j = todo.index(next) else: j = len(todo) todo.append(next) if label is None: print(f" -> {j}") else: print(f" {label} -> {j}") def dump_dfa(self, name: str, dfa: Sequence["DFAState"]) -> None: print("Dump of DFA for", name) for i, state in enumerate(dfa): print(" State", i, state.isfinal and "(final)" or "") for label, next in sorted(state.arcs.items()): print(f" {label} -> {dfa.index(next)}") def simplify_dfa(self, dfa: list["DFAState"]) -> None: # This is not theoretically optimal, but works well enough. # Algorithm: repeatedly look for two states that have the same # set of arcs (same labels pointing to the same nodes) and # unify them, until things stop changing. # dfa is a list of DFAState instances changes = True while changes: changes = False for i, state_i in enumerate(dfa): for j in range(i + 1, len(dfa)): state_j = dfa[j] if state_i == state_j: # print " unify", i, j del dfa[j] for state in dfa: state.unifystate(state_j, state_i) changes = True break def parse_rhs(self) -> tuple["NFAState", "NFAState"]: # RHS: ALT ('|' ALT)* a, z = self.parse_alt() if self.value != "|": return a, z else: aa = NFAState() zz = NFAState() aa.addarc(a) z.addarc(zz) while self.value == "|": self.gettoken() a, z = self.parse_alt() aa.addarc(a) z.addarc(zz) return aa, zz def parse_alt(self) -> tuple["NFAState", "NFAState"]: # ALT: ITEM+ a, b = self.parse_item() while self.value in ("(", "[") or self.type in (token.NAME, token.STRING): c, d = self.parse_item() b.addarc(c) b = d return a, b def parse_item(self) -> tuple["NFAState", "NFAState"]: # ITEM: '[' RHS ']' | ATOM ['+' | '*'] if self.value == "[": self.gettoken() a, z = self.parse_rhs() self.expect(token.OP, "]") a.addarc(z) return a, z else: a, z = self.parse_atom() value = self.value if value not in ("+", "*"): return a, z self.gettoken() z.addarc(a) if value == "+": return a, z else: return a, a def parse_atom(self) -> tuple["NFAState", "NFAState"]: # ATOM: '(' RHS ')' | NAME | STRING if self.value == "(": self.gettoken() a, z = self.parse_rhs() self.expect(token.OP, ")") return a, z elif self.type in (token.NAME, token.STRING): a = NFAState() z = NFAState() a.addarc(z, self.value) self.gettoken() return a, z else: self.raise_error( f"expected (...) or NAME or STRING, got {self.type}/{self.value}" ) def expect(self, type: int, value: Any | None = None) -> str: if self.type != type or (value is not None and self.value != value): self.raise_error(f"expected {type}/{value}, got {self.type}/{self.value}") value = self.value self.gettoken() return value def gettoken(self) -> None: tup = next(self.generator) while tup[0] in (tokenize.COMMENT, tokenize.NL): tup = next(self.generator) self.type, self.value, self.begin, self.end, self.line = tup # print token.tok_name[self.type], repr(self.value) def raise_error(self, msg: str) -> NoReturn: raise SyntaxError( msg, (str(self.filename), self.end[0], self.end[1], self.line) ) class NFAState: arcs: list[tuple[str | None, "NFAState"]] def __init__(self) -> None: self.arcs = [] # list of (label, NFAState) pairs def addarc(self, next: "NFAState", label: str | None = None) -> None: assert label is None or isinstance(label, str) assert isinstance(next, NFAState) self.arcs.append((label, next)) class DFAState: nfaset: dict[NFAState, Any] isfinal: bool arcs: dict[str, "DFAState"] def __init__(self, nfaset: dict[NFAState, Any], final: NFAState) -> None: assert isinstance(nfaset, dict) assert isinstance(next(iter(nfaset)), NFAState) assert isinstance(final, NFAState) self.nfaset = nfaset self.isfinal = final in nfaset self.arcs = {} # map from label to DFAState def addarc(self, next: "DFAState", label: str) -> None: assert isinstance(label, str) assert label not in self.arcs assert isinstance(next, DFAState) self.arcs[label] = next def unifystate(self, old: "DFAState", new: "DFAState") -> None: for label, next in self.arcs.items(): if next is old: self.arcs[label] = new def __eq__(self, other: Any) -> bool: # Equality test -- ignore the nfaset instance variable assert isinstance(other, DFAState) if self.isfinal != other.isfinal: return False # Can't just return self.arcs == other.arcs, because that # would invoke this method recursively, with cycles... if len(self.arcs) != len(other.arcs): return False for label, next in self.arcs.items(): if next is not other.arcs.get(label): return False return True __hash__: Any = None # For Py3 compatibility. def generate_grammar(filename: Path = "Grammar.txt") -> PgenGrammar: p = ParserGenerator(filename) return p.make_grammar()
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/src/blib2to3/pgen2/grammar.py
src/blib2to3/pgen2/grammar.py
# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """This module defines the data structures used to represent a grammar. These are a bit arcane because they are derived from the data structures used by Python's 'pgen' parser generator. There's also a table here mapping operators to their names in the token module; the Python tokenize module reports all operators as the fallback token code OP, but the parser needs the actual token code. """ # Python imports import os import pickle import tempfile from typing import Any, Optional, TypeVar, Union # Local imports from . import token _P = TypeVar("_P", bound="Grammar") Label = tuple[int, Optional[str]] DFA = list[list[tuple[int, int]]] DFAS = tuple[DFA, dict[int, int]] Path = Union[str, "os.PathLike[str]"] class Grammar: """Pgen parsing tables conversion class. Once initialized, this class supplies the grammar tables for the parsing engine implemented by parse.py. The parsing engine accesses the instance variables directly. The class here does not provide initialization of the tables; several subclasses exist to do this (see the conv and pgen modules). The load() method reads the tables from a pickle file, which is much faster than the other ways offered by subclasses. The pickle file is written by calling dump() (after loading the grammar tables using a subclass). The report() method prints a readable representation of the tables to stdout, for debugging. The instance variables are as follows: symbol2number -- a dict mapping symbol names to numbers. Symbol numbers are always 256 or higher, to distinguish them from token numbers, which are between 0 and 255 (inclusive). number2symbol -- a dict mapping numbers to symbol names; these two are each other's inverse. states -- a list of DFAs, where each DFA is a list of states, each state is a list of arcs, and each arc is a (i, j) pair where i is a label and j is a state number. The DFA number is the index into this list. (This name is slightly confusing.) Final states are represented by a special arc of the form (0, j) where j is its own state number. dfas -- a dict mapping symbol numbers to (DFA, first) pairs, where DFA is an item from the states list above, and first is a set of tokens that can begin this grammar rule (represented by a dict whose values are always 1). labels -- a list of (x, y) pairs where x is either a token number or a symbol number, and y is either None or a string; the strings are keywords. The label number is the index in this list; label numbers are used to mark state transitions (arcs) in the DFAs. start -- the number of the grammar's start symbol. keywords -- a dict mapping keyword strings to arc labels. tokens -- a dict mapping token numbers to arc labels. """ def __init__(self) -> None: self.symbol2number: dict[str, int] = {} self.number2symbol: dict[int, str] = {} self.states: list[DFA] = [] self.dfas: dict[int, DFAS] = {} self.labels: list[Label] = [(0, "EMPTY")] self.keywords: dict[str, int] = {} self.soft_keywords: dict[str, int] = {} self.tokens: dict[int, int] = {} self.symbol2label: dict[str, int] = {} self.version: tuple[int, int] = (0, 0) self.start = 256 # Python 3.7+ parses async as a keyword, not an identifier self.async_keywords = False def dump(self, filename: Path) -> None: """Dump the grammar tables to a pickle file.""" # mypyc generates objects that don't have a __dict__, but they # do have __getstate__ methods that will return an equivalent # dictionary if hasattr(self, "__dict__"): d = self.__dict__ else: d = self.__getstate__() # type: ignore with tempfile.NamedTemporaryFile( dir=os.path.dirname(filename), delete=False ) as f: pickle.dump(d, f, pickle.HIGHEST_PROTOCOL) os.replace(f.name, filename) def _update(self, attrs: dict[str, Any]) -> None: for k, v in attrs.items(): setattr(self, k, v) def load(self, filename: Path) -> None: """Load the grammar tables from a pickle file.""" with open(filename, "rb") as f: d = pickle.load(f) self._update(d) def loads(self, pkl: bytes) -> None: """Load the grammar tables from a pickle bytes object.""" self._update(pickle.loads(pkl)) def copy(self: _P) -> _P: """ Copy the grammar. """ new = self.__class__() for dict_attr in ( "symbol2number", "number2symbol", "dfas", "keywords", "soft_keywords", "tokens", "symbol2label", ): setattr(new, dict_attr, getattr(self, dict_attr).copy()) new.labels = self.labels[:] new.states = self.states[:] new.start = self.start new.version = self.version new.async_keywords = self.async_keywords return new def report(self) -> None: """Dump the grammar tables to standard output, for debugging.""" from pprint import pprint print("s2n") pprint(self.symbol2number) print("n2s") pprint(self.number2symbol) print("states") pprint(self.states) print("dfas") pprint(self.dfas) print("labels") pprint(self.labels) print("start", self.start) # Map from operator to number (since tokenize doesn't do this) opmap_raw = """ ( LPAR ) RPAR [ LSQB ] RSQB : COLON , COMMA ; SEMI + PLUS - MINUS * STAR / SLASH | VBAR & AMPER < LESS > GREATER = EQUAL . DOT % PERCENT ` BACKQUOTE { LBRACE } RBRACE @ AT @= ATEQUAL == EQEQUAL != NOTEQUAL <> NOTEQUAL <= LESSEQUAL >= GREATEREQUAL ~ TILDE ^ CIRCUMFLEX << LEFTSHIFT >> RIGHTSHIFT ** DOUBLESTAR += PLUSEQUAL -= MINEQUAL *= STAREQUAL /= SLASHEQUAL %= PERCENTEQUAL &= AMPEREQUAL |= VBAREQUAL ^= CIRCUMFLEXEQUAL <<= LEFTSHIFTEQUAL >>= RIGHTSHIFTEQUAL **= DOUBLESTAREQUAL // DOUBLESLASH //= DOUBLESLASHEQUAL -> RARROW := COLONEQUAL ! BANG """ opmap = {} for line in opmap_raw.splitlines(): if line: op, name = line.split() opmap[op] = getattr(token, name)
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/src/blib2to3/pgen2/__init__.py
src/blib2to3/pgen2/__init__.py
# Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """The pgen2 package."""
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/src/black/handle_ipynb_magics.py
src/black/handle_ipynb_magics.py
"""Functions to process IPython magics with.""" import ast import collections import dataclasses import re import secrets from functools import lru_cache from importlib.util import find_spec from typing import TypeGuard from black.mode import Mode from black.output import out from black.report import NothingChanged TRANSFORMED_MAGICS = frozenset(( "get_ipython().run_cell_magic", "get_ipython().system", "get_ipython().getoutput", "get_ipython().run_line_magic", )) TOKENS_TO_IGNORE = frozenset(( "ENDMARKER", "NL", "NEWLINE", "COMMENT", "DEDENT", "UNIMPORTANT_WS", "ESCAPED_NL", )) PYTHON_CELL_MAGICS = frozenset(( "capture", "prun", "pypy", "python", "python3", "time", "timeit", )) @dataclasses.dataclass(frozen=True) class Replacement: mask: str src: str @lru_cache def jupyter_dependencies_are_installed(*, warn: bool) -> bool: installed = ( find_spec("tokenize_rt") is not None and find_spec("IPython") is not None ) if not installed and warn: msg = ( "Skipping .ipynb files as Jupyter dependencies are not installed.\n" 'You can fix this by running ``pip install "black[jupyter]"``' ) out(msg) return installed def validate_cell(src: str, mode: Mode) -> None: r"""Check that cell does not already contain TransformerManager transformations, or non-Python cell magics, which might cause tokenizer_rt to break because of indentations. If a cell contains ``!ls``, then it'll be transformed to ``get_ipython().system('ls')``. However, if the cell originally contained ``get_ipython().system('ls')``, then it would get transformed in the same way: >>> TransformerManager().transform_cell("get_ipython().system('ls')") "get_ipython().system('ls')\n" >>> TransformerManager().transform_cell("!ls") "get_ipython().system('ls')\n" Due to the impossibility of safely roundtripping in such situations, cells containing transformed magics will be ignored. """ if any(transformed_magic in src for transformed_magic in TRANSFORMED_MAGICS): raise NothingChanged line = _get_code_start(src) if line.startswith("%%") and ( line.split(maxsplit=1)[0][2:] not in PYTHON_CELL_MAGICS | mode.python_cell_magics ): raise NothingChanged def remove_trailing_semicolon(src: str) -> tuple[str, bool]: """Remove trailing semicolon from Jupyter notebook cell. For example, fig, ax = plt.subplots() ax.plot(x_data, y_data); # plot data would become fig, ax = plt.subplots() ax.plot(x_data, y_data) # plot data Mirrors the logic in `quiet` from `IPython.core.displayhook`, but uses ``tokenize_rt`` so that round-tripping works fine. """ from tokenize_rt import reversed_enumerate, src_to_tokens, tokens_to_src tokens = src_to_tokens(src) trailing_semicolon = False for idx, token in reversed_enumerate(tokens): if token.name in TOKENS_TO_IGNORE: continue if token.name == "OP" and token.src == ";": del tokens[idx] trailing_semicolon = True break if not trailing_semicolon: return src, False return tokens_to_src(tokens), True def put_trailing_semicolon_back(src: str, has_trailing_semicolon: bool) -> str: """Put trailing semicolon back if cell originally had it. Mirrors the logic in `quiet` from `IPython.core.displayhook`, but uses ``tokenize_rt`` so that round-tripping works fine. """ if not has_trailing_semicolon: return src from tokenize_rt import reversed_enumerate, src_to_tokens, tokens_to_src tokens = src_to_tokens(src) for idx, token in reversed_enumerate(tokens): if token.name in TOKENS_TO_IGNORE: continue tokens[idx] = token._replace(src=token.src + ";") break else: # pragma: nocover raise AssertionError( "INTERNAL ERROR: Was not able to reinstate trailing semicolon. " "Please report a bug on https://github.com/psf/black/issues. " ) from None return str(tokens_to_src(tokens)) def mask_cell(src: str) -> tuple[str, list[Replacement]]: """Mask IPython magics so content becomes parseable Python code. For example, %matplotlib inline 'foo' becomes b"25716f358c32750" 'foo' The replacements are returned, along with the transformed code. """ replacements: list[Replacement] = [] try: ast.parse(src) except SyntaxError: # Might have IPython magics, will process below. pass else: # Syntax is fine, nothing to mask, early return. return src, replacements from IPython.core.inputtransformer2 import TransformerManager transformer_manager = TransformerManager() # A side effect of the following transformation is that it also removes any # empty lines at the beginning of the cell. transformed = transformer_manager.transform_cell(src) transformed, cell_magic_replacements = replace_cell_magics(transformed) replacements += cell_magic_replacements transformed = transformer_manager.transform_cell(transformed) transformed, magic_replacements = replace_magics(transformed) if len(transformed.strip().splitlines()) != len(src.strip().splitlines()): # Multi-line magic, not supported. raise NothingChanged replacements += magic_replacements return transformed, replacements def create_token(n_chars: int) -> str: """Create a randomly generated token that is n_chars characters long.""" assert n_chars > 0 n_bytes = max(n_chars // 2 - 1, 1) token = secrets.token_hex(n_bytes) if len(token) + 3 > n_chars: token = token[:-1] # We use a bytestring so that the string does not get interpreted # as a docstring. return f'b"{token}"' def get_token(src: str, magic: str) -> str: """Return randomly generated token to mask IPython magic with. For example, if 'magic' was `%matplotlib inline`, then a possible token to mask it with would be `"43fdd17f7e5ddc83"`. The token will be the same length as the magic, and we make sure that it was not already present anywhere else in the cell. """ assert magic n_chars = len(magic) token = create_token(n_chars) counter = 0 while token in src: token = create_token(n_chars) counter += 1 if counter > 100: raise AssertionError( "INTERNAL ERROR: Black was not able to replace IPython magic. " "Please report a bug on https://github.com/psf/black/issues. " f"The magic might be helpful: {magic}" ) from None return token def replace_cell_magics(src: str) -> tuple[str, list[Replacement]]: r"""Replace cell magic with token. Note that 'src' will already have been processed by IPython's TransformerManager().transform_cell. Example, get_ipython().run_cell_magic('t', '-n1', 'ls =!ls\n') becomes "a794." ls =!ls The replacement, along with the transformed code, is returned. """ replacements: list[Replacement] = [] tree = ast.parse(src) cell_magic_finder = CellMagicFinder() cell_magic_finder.visit(tree) if cell_magic_finder.cell_magic is None: return src, replacements header = cell_magic_finder.cell_magic.header mask = get_token(src, header) replacements.append(Replacement(mask=mask, src=header)) return f"{mask}\n{cell_magic_finder.cell_magic.body}", replacements def replace_magics(src: str) -> tuple[str, list[Replacement]]: """Replace magics within body of cell. Note that 'src' will already have been processed by IPython's TransformerManager().transform_cell. Example, this get_ipython().run_line_magic('matplotlib', 'inline') 'foo' becomes "5e67db56d490fd39" 'foo' The replacement, along with the transformed code, are returned. """ replacements = [] magic_finder = MagicFinder() magic_finder.visit(ast.parse(src)) new_srcs = [] for i, line in enumerate(src.split("\n"), start=1): if i in magic_finder.magics: offsets_and_magics = magic_finder.magics[i] if len(offsets_and_magics) != 1: # pragma: nocover raise AssertionError( f"Expecting one magic per line, got: {offsets_and_magics}\n" "Please report a bug on https://github.com/psf/black/issues." ) col_offset, magic = ( offsets_and_magics[0].col_offset, offsets_and_magics[0].magic, ) mask = get_token(src, magic) replacements.append(Replacement(mask=mask, src=magic)) line = line[:col_offset] + mask new_srcs.append(line) return "\n".join(new_srcs), replacements def unmask_cell(src: str, replacements: list[Replacement]) -> str: """Remove replacements from cell. For example "9b20" foo = bar becomes %%time foo = bar """ for replacement in replacements: src = src.replace(replacement.mask, replacement.src) return src def _get_code_start(src: str) -> str: """Provides the first line where the code starts. Iterates over lines of code until it finds the first line that doesn't contain only empty spaces and comments. It removes any empty spaces at the start of the line and returns it. If such line doesn't exist, it returns an empty string. """ for match in re.finditer(".+", src): line = match.group(0).lstrip() if line and not line.startswith("#"): return line return "" def _is_ipython_magic(node: ast.expr) -> TypeGuard[ast.Attribute]: """Check if attribute is IPython magic. Note that the source of the abstract syntax tree will already have been processed by IPython's TransformerManager().transform_cell. """ return ( isinstance(node, ast.Attribute) and isinstance(node.value, ast.Call) and isinstance(node.value.func, ast.Name) and node.value.func.id == "get_ipython" ) def _get_str_args(args: list[ast.expr]) -> list[str]: str_args = [] for arg in args: assert isinstance(arg, ast.Constant) and isinstance(arg.value, str) str_args.append(arg.value) return str_args @dataclasses.dataclass(frozen=True) class CellMagic: name: str params: str | None body: str @property def header(self) -> str: if self.params: return f"%%{self.name} {self.params}" return f"%%{self.name}" # ast.NodeVisitor + dataclass = breakage under mypyc. class CellMagicFinder(ast.NodeVisitor): r"""Find cell magics. Note that the source of the abstract syntax tree will already have been processed by IPython's TransformerManager().transform_cell. For example, %%time\n foo() would have been transformed to get_ipython().run_cell_magic('time', '', 'foo()\n') and we look for instances of the latter. """ def __init__(self, cell_magic: CellMagic | None = None) -> None: self.cell_magic = cell_magic def visit_Expr(self, node: ast.Expr) -> None: """Find cell magic, extract header and body.""" if ( isinstance(node.value, ast.Call) and _is_ipython_magic(node.value.func) and node.value.func.attr == "run_cell_magic" ): args = _get_str_args(node.value.args) self.cell_magic = CellMagic(name=args[0], params=args[1], body=args[2]) self.generic_visit(node) @dataclasses.dataclass(frozen=True) class OffsetAndMagic: col_offset: int magic: str # Unsurprisingly, subclassing ast.NodeVisitor means we can't use dataclasses here # as mypyc will generate broken code. class MagicFinder(ast.NodeVisitor): """Visit cell to look for get_ipython calls. Note that the source of the abstract syntax tree will already have been processed by IPython's TransformerManager().transform_cell. For example, %matplotlib inline would have been transformed to get_ipython().run_line_magic('matplotlib', 'inline') and we look for instances of the latter (and likewise for other types of magics). """ def __init__(self) -> None: self.magics: dict[int, list[OffsetAndMagic]] = collections.defaultdict(list) def visit_Assign(self, node: ast.Assign) -> None: """Look for system assign magics. For example, black_version = !black --version env = %env var would have been (respectively) transformed to black_version = get_ipython().getoutput('black --version') env = get_ipython().run_line_magic('env', 'var') and we look for instances of any of the latter. """ if isinstance(node.value, ast.Call) and _is_ipython_magic(node.value.func): args = _get_str_args(node.value.args) if node.value.func.attr == "getoutput": src = f"!{args[0]}" elif node.value.func.attr == "run_line_magic": src = f"%{args[0]}" if args[1]: src += f" {args[1]}" else: raise AssertionError( f"Unexpected IPython magic {node.value.func.attr!r} found. " "Please report a bug on https://github.com/psf/black/issues." ) from None self.magics[node.value.lineno].append( OffsetAndMagic(node.value.col_offset, src) ) self.generic_visit(node) def visit_Expr(self, node: ast.Expr) -> None: """Look for magics in body of cell. For examples, !ls !!ls ?ls ??ls would (respectively) get transformed to get_ipython().system('ls') get_ipython().getoutput('ls') get_ipython().run_line_magic('pinfo', 'ls') get_ipython().run_line_magic('pinfo2', 'ls') and we look for instances of any of the latter. """ if isinstance(node.value, ast.Call) and _is_ipython_magic(node.value.func): args = _get_str_args(node.value.args) if node.value.func.attr == "run_line_magic": if args[0] == "pinfo": src = f"?{args[1]}" elif args[0] == "pinfo2": src = f"??{args[1]}" else: src = f"%{args[0]}" if args[1]: src += f" {args[1]}" elif node.value.func.attr == "system": src = f"!{args[0]}" elif node.value.func.attr == "getoutput": src = f"!!{args[0]}" else: raise NothingChanged # unsupported magic. self.magics[node.value.lineno].append( OffsetAndMagic(node.value.col_offset, src) ) self.generic_visit(node)
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/src/black/lines.py
src/black/lines.py
import itertools import math from collections.abc import Callable, Iterator, Sequence from dataclasses import dataclass, field from typing import Optional, TypeVar, Union, cast from black.brackets import COMMA_PRIORITY, DOT_PRIORITY, BracketTracker from black.mode import Mode, Preview from black.nodes import ( BRACKETS, CLOSING_BRACKETS, OPENING_BRACKETS, STANDALONE_COMMENT, TEST_DESCENDANTS, child_towards, is_docstring, is_import, is_multiline_string, is_one_sequence_between, is_type_comment, is_type_ignore_comment, is_with_or_async_with_stmt, make_simple_prefix, replace_child, syms, whitespace, ) from black.strings import str_width from blib2to3.pgen2 import token from blib2to3.pytree import Leaf, Node # types T = TypeVar("T") Index = int LeafID = int LN = Union[Leaf, Node] @dataclass class Line: """Holds leaves and comments. Can be printed with `str(line)`.""" mode: Mode = field(repr=False) depth: int = 0 leaves: list[Leaf] = field(default_factory=list) # keys ordered like `leaves` comments: dict[LeafID, list[Leaf]] = field(default_factory=dict) bracket_tracker: BracketTracker = field(default_factory=BracketTracker) inside_brackets: bool = False should_split_rhs: bool = False magic_trailing_comma: Leaf | None = None def append( self, leaf: Leaf, preformatted: bool = False, track_bracket: bool = False ) -> None: """Add a new `leaf` to the end of the line. Unless `preformatted` is True, the `leaf` will receive a new consistent whitespace prefix and metadata applied by :class:`BracketTracker`. Trailing commas are maybe removed, unpacked for loop variables are demoted from being delimiters. Inline comments are put aside. """ has_value = ( leaf.type in BRACKETS # empty fstring and tstring middles must not be truncated or leaf.type in (token.FSTRING_MIDDLE, token.TSTRING_MIDDLE) or bool(leaf.value.strip()) ) if not has_value: return if leaf.type == token.COLON and self.is_class_paren_empty: del self.leaves[-2:] if self.leaves and not preformatted: # Note: at this point leaf.prefix should be empty except for # imports, for which we only preserve newlines. leaf.prefix += whitespace( leaf, complex_subscript=self.is_complex_subscript(leaf), mode=self.mode, ) if self.inside_brackets or not preformatted or track_bracket: self.bracket_tracker.mark(leaf) if self.mode.magic_trailing_comma: if self.has_magic_trailing_comma(leaf): self.magic_trailing_comma = leaf elif self.has_magic_trailing_comma(leaf): self.remove_trailing_comma() if not self.append_comment(leaf): self.leaves.append(leaf) def append_safe(self, leaf: Leaf, preformatted: bool = False) -> None: """Like :func:`append()` but disallow invalid standalone comment structure. Raises ValueError when any `leaf` is appended after a standalone comment or when a standalone comment is not the first leaf on the line. """ if ( self.bracket_tracker.depth == 0 or self.bracket_tracker.any_open_for_or_lambda() ): if self.is_comment: raise ValueError("cannot append to standalone comments") if self.leaves and leaf.type == STANDALONE_COMMENT: raise ValueError( "cannot append standalone comments to a populated line" ) self.append(leaf, preformatted=preformatted) @property def is_comment(self) -> bool: """Is this line a standalone comment?""" return len(self.leaves) == 1 and self.leaves[0].type == STANDALONE_COMMENT @property def is_decorator(self) -> bool: """Is this line a decorator?""" return bool(self) and self.leaves[0].type == token.AT @property def is_import(self) -> bool: """Is this an import line?""" return bool(self) and is_import(self.leaves[0]) @property def is_with_or_async_with_stmt(self) -> bool: """Is this a with_stmt line?""" return bool(self) and is_with_or_async_with_stmt(self.leaves[0]) @property def is_class(self) -> bool: """Is this line a class definition?""" return ( bool(self) and self.leaves[0].type == token.NAME and self.leaves[0].value == "class" ) @property def is_stub_class(self) -> bool: """Is this line a class definition with a body consisting only of "..."?""" return self.is_class and self.leaves[-3:] == [ Leaf(token.DOT, ".") for _ in range(3) ] @property def is_def(self) -> bool: """Is this a function definition? (Also returns True for async defs.)""" try: first_leaf = self.leaves[0] except IndexError: return False try: second_leaf: Leaf | None = self.leaves[1] except IndexError: second_leaf = None return (first_leaf.type == token.NAME and first_leaf.value == "def") or ( first_leaf.type == token.ASYNC and second_leaf is not None and second_leaf.type == token.NAME and second_leaf.value == "def" ) @property def is_stub_def(self) -> bool: """Is this line a function definition with a body consisting only of "..."?""" return self.is_def and self.leaves[-4:] == [Leaf(token.COLON, ":")] + [ Leaf(token.DOT, ".") for _ in range(3) ] @property def is_class_paren_empty(self) -> bool: """Is this a class with no base classes but using parentheses? Those are unnecessary and should be removed. """ return ( bool(self) and len(self.leaves) == 4 and self.is_class and self.leaves[2].type == token.LPAR and self.leaves[2].value == "(" and self.leaves[3].type == token.RPAR and self.leaves[3].value == ")" ) @property def _is_triple_quoted_string(self) -> bool: """Is the line a triple quoted string?""" if not self or self.leaves[0].type != token.STRING: return False value = self.leaves[0].value if value.startswith(('"""', "'''")): return True if value.startswith(("r'''", 'r"""', "R'''", 'R"""')): return True return False @property def is_docstring(self) -> bool: """Is the line a docstring?""" return bool(self) and is_docstring(self.leaves[0]) @property def is_chained_assignment(self) -> bool: """Is the line a chained assignment""" return [leaf.type for leaf in self.leaves].count(token.EQUAL) > 1 @property def opens_block(self) -> bool: """Does this line open a new level of indentation.""" if len(self.leaves) == 0: return False return self.leaves[-1].type == token.COLON def is_fmt_pass_converted( self, *, first_leaf_matches: Callable[[Leaf], bool] | None = None ) -> bool: """Is this line converted from fmt off/skip code? If first_leaf_matches is not None, it only returns True if the first leaf of converted code matches. """ if len(self.leaves) != 1: return False leaf = self.leaves[0] if ( leaf.type != STANDALONE_COMMENT or leaf.fmt_pass_converted_first_leaf is None ): return False return first_leaf_matches is None or first_leaf_matches( leaf.fmt_pass_converted_first_leaf ) def contains_standalone_comments(self) -> bool: """If so, needs to be split before emitting.""" for leaf in self.leaves: if leaf.type == STANDALONE_COMMENT: return True return False def contains_implicit_multiline_string_with_comments(self) -> bool: """Chck if we have an implicit multiline string with comments on the line""" for leaf_type, leaf_group_iterator in itertools.groupby( self.leaves, lambda leaf: leaf.type ): if leaf_type != token.STRING: continue leaf_list = list(leaf_group_iterator) if len(leaf_list) == 1: continue for leaf in leaf_list: if self.comments_after(leaf): return True return False def contains_uncollapsable_type_comments(self) -> bool: ignored_ids = set() try: last_leaf = self.leaves[-1] ignored_ids.add(id(last_leaf)) if last_leaf.type == token.COMMA or ( last_leaf.type == token.RPAR and not last_leaf.value ): # When trailing commas or optional parens are inserted by Black for # consistency, comments after the previous last element are not moved # (they don't have to, rendering will still be correct). So we ignore # trailing commas and invisible. last_leaf = self.leaves[-2] ignored_ids.add(id(last_leaf)) except IndexError: return False # A type comment is uncollapsable if it is attached to a leaf # that isn't at the end of the line (since that could cause it # to get associated to a different argument) or if there are # comments before it (since that could cause it to get hidden # behind a comment. comment_seen = False for leaf_id, comments in self.comments.items(): for comment in comments: if is_type_comment(comment, mode=self.mode): if comment_seen or ( not is_type_ignore_comment(comment, mode=self.mode) and leaf_id not in ignored_ids ): return True comment_seen = True return False def contains_unsplittable_type_ignore(self) -> bool: if not self.leaves: return False # If a 'type: ignore' is attached to the end of a line, we # can't split the line, because we can't know which of the # subexpressions the ignore was meant to apply to. # # We only want this to apply to actual physical lines from the # original source, though: we don't want the presence of a # 'type: ignore' at the end of a multiline expression to # justify pushing it all onto one line. Thus we # (unfortunately) need to check the actual source lines and # only report an unsplittable 'type: ignore' if this line was # one line in the original code. # Grab the first and last line numbers, skipping generated leaves first_line = next((leaf.lineno for leaf in self.leaves if leaf.lineno != 0), 0) last_line = next( (leaf.lineno for leaf in reversed(self.leaves) if leaf.lineno != 0), 0 ) if first_line == last_line: # We look at the last two leaves since a comma or an # invisible paren could have been added at the end of the # line. for node in self.leaves[-2:]: for comment in self.comments.get(id(node), []): if is_type_ignore_comment(comment, mode=self.mode): return True return False def contains_multiline_strings(self) -> bool: return any(is_multiline_string(leaf) for leaf in self.leaves) def has_magic_trailing_comma(self, closing: Leaf) -> bool: """Return True if we have a magic trailing comma, that is when: - there's a trailing comma here - it's not from single-element square bracket indexing - it's not a one-tuple """ if not ( closing.type in CLOSING_BRACKETS and self.leaves and self.leaves[-1].type == token.COMMA ): return False if closing.type == token.RBRACE: return True if closing.type == token.RSQB: if ( closing.parent is not None and closing.parent.type == syms.trailer and closing.opening_bracket is not None and is_one_sequence_between( closing.opening_bracket, closing, self.leaves, brackets=(token.LSQB, token.RSQB), ) ): assert closing.prev_sibling is not None assert closing.prev_sibling.type == syms.subscriptlist return False return True if self.is_import: return True if closing.opening_bracket is not None and not is_one_sequence_between( closing.opening_bracket, closing, self.leaves ): return True return False def append_comment(self, comment: Leaf) -> bool: """Add an inline or standalone comment to the line.""" if ( comment.type == STANDALONE_COMMENT and self.bracket_tracker.any_open_brackets() ): comment.prefix = "" return False if comment.type != token.COMMENT: return False if not self.leaves: comment.type = STANDALONE_COMMENT comment.prefix = "" return False last_leaf = self.leaves[-1] if ( last_leaf.type == token.RPAR and not last_leaf.value and last_leaf.parent and len(list(last_leaf.parent.leaves())) <= 3 and not is_type_comment(comment, mode=self.mode) ): # Comments on an optional parens wrapping a single leaf should belong to # the wrapped node except if it's a type comment. Pinning the comment like # this avoids unstable formatting caused by comment migration. if len(self.leaves) < 2: comment.type = STANDALONE_COMMENT comment.prefix = "" return False last_leaf = self.leaves[-2] self.comments.setdefault(id(last_leaf), []).append(comment) return True def comments_after(self, leaf: Leaf) -> list[Leaf]: """Generate comments that should appear directly after `leaf`.""" return self.comments.get(id(leaf), []) def remove_trailing_comma(self) -> None: """Remove the trailing comma and moves the comments attached to it.""" trailing_comma = self.leaves.pop() trailing_comma_comments = self.comments.pop(id(trailing_comma), []) self.comments.setdefault(id(self.leaves[-1]), []).extend( trailing_comma_comments ) def is_complex_subscript(self, leaf: Leaf) -> bool: """Return True iff `leaf` is part of a slice with non-trivial exprs.""" open_lsqb = self.bracket_tracker.get_open_lsqb() if open_lsqb is None: return False subscript_start = open_lsqb.next_sibling if isinstance(subscript_start, Node): if subscript_start.type == syms.listmaker: return False if subscript_start.type == syms.subscriptlist: subscript_start = child_towards(subscript_start, leaf) return subscript_start is not None and any( n.type in TEST_DESCENDANTS for n in subscript_start.pre_order() ) def enumerate_with_length( self, is_reversed: bool = False ) -> Iterator[tuple[Index, Leaf, int]]: """Return an enumeration of leaves with their length. Stops prematurely on multiline strings and standalone comments. """ op = cast( Callable[[Sequence[Leaf]], Iterator[tuple[Index, Leaf]]], enumerate_reversed if is_reversed else enumerate, ) for index, leaf in op(self.leaves): length = len(leaf.prefix) + len(leaf.value) if "\n" in leaf.value: return # Multiline strings, we can't continue. for comment in self.comments_after(leaf): length += len(comment.value) yield index, leaf, length def clone(self) -> "Line": return Line( mode=self.mode, depth=self.depth, inside_brackets=self.inside_brackets, should_split_rhs=self.should_split_rhs, magic_trailing_comma=self.magic_trailing_comma, ) def __str__(self) -> str: """Render the line.""" if not self: return "\n" indent = " " * self.depth leaves = iter(self.leaves) first = next(leaves) res = f"{first.prefix}{indent}{first.value}" res += "".join(str(leaf) for leaf in leaves) comments_iter = itertools.chain.from_iterable(self.comments.values()) comments = [str(comment) for comment in comments_iter] res += "".join(comments) return res + "\n" def __bool__(self) -> bool: """Return True if the line has leaves or comments.""" return bool(self.leaves or self.comments) @dataclass class RHSResult: """Intermediate split result from a right hand split.""" head: Line body: Line tail: Line opening_bracket: Leaf closing_bracket: Leaf @dataclass class LinesBlock: """Class that holds information about a block of formatted lines. This is introduced so that the EmptyLineTracker can look behind the standalone comments and adjust their empty lines for class or def lines. """ mode: Mode previous_block: Optional["LinesBlock"] original_line: Line before: int = 0 content_lines: list[str] = field(default_factory=list) after: int = 0 form_feed: bool = False def all_lines(self) -> list[str]: empty_line = str(Line(mode=self.mode)) prefix = make_simple_prefix(self.before, self.form_feed, empty_line) return [prefix] + self.content_lines + [empty_line * self.after] @dataclass class EmptyLineTracker: """Provides a stateful method that returns the number of potential extra empty lines needed before and after the currently processed line. Note: this tracker works on lines that haven't been split yet. It assumes the prefix of the first leaf consists of optional newlines. Those newlines are consumed by `maybe_empty_lines()` and included in the computation. """ mode: Mode previous_line: Line | None = None previous_block: LinesBlock | None = None previous_defs: list[Line] = field(default_factory=list) semantic_leading_comment: LinesBlock | None = None def maybe_empty_lines(self, current_line: Line) -> LinesBlock: """Return the number of extra empty lines before and after the `current_line`. This is for separating `def`, `async def` and `class` with extra empty lines (two on module-level). """ form_feed = ( current_line.depth == 0 and bool(current_line.leaves) and "\f\n" in current_line.leaves[0].prefix ) before, after = self._maybe_empty_lines(current_line) previous_after = self.previous_block.after if self.previous_block else 0 before = max(0, before - previous_after) if Preview.fix_module_docstring_detection in self.mode: # Always have one empty line after a module docstring if self._line_is_module_docstring(current_line): before = 1 else: if ( # Always have one empty line after a module docstring self.previous_block and self.previous_block.previous_block is None and len(self.previous_block.original_line.leaves) == 1 and self.previous_block.original_line.is_docstring and not (current_line.is_class or current_line.is_def) ): before = 1 block = LinesBlock( mode=self.mode, previous_block=self.previous_block, original_line=current_line, before=before, after=after, form_feed=form_feed, ) # Maintain the semantic_leading_comment state. if current_line.is_comment: if self.previous_line is None or ( not self.previous_line.is_decorator # `or before` means this comment already has an empty line before and (not self.previous_line.is_comment or before) and (self.semantic_leading_comment is None or before) ): self.semantic_leading_comment = block # `or before` means this decorator already has an empty line before elif not current_line.is_decorator or before: self.semantic_leading_comment = None self.previous_line = current_line self.previous_block = block return block def _line_is_module_docstring(self, current_line: Line) -> bool: previous_block = self.previous_block if not previous_block: return False if ( len(previous_block.original_line.leaves) != 1 or not previous_block.original_line.is_docstring or current_line.is_class or current_line.is_def ): return False while previous_block := previous_block.previous_block: if not previous_block.original_line.is_comment: return False return True def _maybe_empty_lines(self, current_line: Line) -> tuple[int, int]: max_allowed = 1 if current_line.depth == 0: max_allowed = 1 if self.mode.is_pyi else 2 if current_line.leaves: # Consume the first leaf's extra newlines. first_leaf = current_line.leaves[0] before = first_leaf.prefix.count("\n") before = min(before, max_allowed) first_leaf.prefix = "" else: before = 0 user_had_newline = bool(before) depth = current_line.depth # Mutate self.previous_defs, remainder of this function should be pure previous_def = None while self.previous_defs and self.previous_defs[-1].depth >= depth: previous_def = self.previous_defs.pop() if current_line.is_def or current_line.is_class: self.previous_defs.append(current_line) if self.previous_line is None: # Don't insert empty lines before the first line in the file. return 0, 0 if current_line.is_docstring: if self.previous_line.is_class: return 0, 1 if self.previous_line.opens_block and self.previous_line.is_def: return 0, 0 if previous_def is not None: assert self.previous_line is not None if self.mode.is_pyi: if previous_def.is_class and not previous_def.is_stub_class: before = 1 elif depth and not current_line.is_def and self.previous_line.is_def: # Empty lines between attributes and methods should be preserved. before = 1 if user_had_newline else 0 elif depth: before = 0 else: before = 1 else: if depth: before = 1 elif ( not depth and previous_def.depth and current_line.leaves[-1].type == token.COLON and ( current_line.leaves[0].value not in ("with", "try", "for", "while", "if", "match") ) ): # We shouldn't add two newlines between an indented function and # a dependent non-indented clause. This is to avoid issues with # conditional function definitions that are technically top-level # and therefore get two trailing newlines, but look weird and # inconsistent when they're followed by elif, else, etc. This is # worse because these functions only get *one* preceding newline # already. before = 1 else: before = 2 if current_line.is_decorator or current_line.is_def or current_line.is_class: return self._maybe_empty_lines_for_class_or_def( current_line, before, user_had_newline ) if ( self.previous_line.is_import and self.previous_line.depth == 0 and current_line.depth == 0 and not current_line.is_import and not current_line.is_fmt_pass_converted(first_leaf_matches=is_import) and Preview.always_one_newline_after_import in self.mode ): return 1, 0 if ( self.previous_line.is_import and not current_line.is_import and not current_line.is_fmt_pass_converted(first_leaf_matches=is_import) and depth == self.previous_line.depth ): return (before or 1), 0 return before, 0 def _maybe_empty_lines_for_class_or_def( self, current_line: Line, before: int, user_had_newline: bool ) -> tuple[int, int]: assert self.previous_line is not None if self.previous_line.is_decorator: if self.mode.is_pyi and current_line.is_stub_class: # Insert an empty line after a decorated stub class return 0, 1 return 0, 0 if self.previous_line.depth < current_line.depth and ( self.previous_line.is_class or self.previous_line.is_def ): if self.mode.is_pyi: return 0, 0 return 1 if user_had_newline else 0, 0 comment_to_add_newlines: LinesBlock | None = None if ( self.previous_line.is_comment and self.previous_line.depth == current_line.depth and before == 0 ): slc = self.semantic_leading_comment if ( slc is not None and slc.previous_block is not None and not slc.previous_block.original_line.is_class and not slc.previous_block.original_line.opens_block and slc.before <= 1 ): comment_to_add_newlines = slc else: return 0, 0 if self.mode.is_pyi: if current_line.is_class or self.previous_line.is_class: if self.previous_line.depth < current_line.depth: newlines = 0 elif self.previous_line.depth > current_line.depth: newlines = 1 elif current_line.is_stub_class and self.previous_line.is_stub_class: # No blank line between classes with an empty body newlines = 0 else: newlines = 1 # Don't inspect the previous line if it's part of the body of the previous # statement in the same level, we always want a blank line if there's # something with a body preceding. elif self.previous_line.depth > current_line.depth: newlines = 1 elif ( current_line.is_def or current_line.is_decorator ) and not self.previous_line.is_def: if current_line.depth: # In classes empty lines between attributes and methods should # be preserved. newlines = min(1, before) else: # Blank line between a block of functions (maybe with preceding # decorators) and a block of non-functions newlines = 1 else: newlines = 0 else: newlines = 1 if current_line.depth else 2 # If a user has left no space after a dummy implementation, don't insert # new lines. This is useful for instance for @overload or Protocols. if self.previous_line.is_stub_def and not user_had_newline: newlines = 0 if comment_to_add_newlines is not None: previous_block = comment_to_add_newlines.previous_block if previous_block is not None: comment_to_add_newlines.before = ( max(comment_to_add_newlines.before, newlines) - previous_block.after ) newlines = 0 return newlines, 0 def enumerate_reversed(sequence: Sequence[T]) -> Iterator[tuple[Index, T]]: """Like `reversed(enumerate(sequence))` if that were possible.""" index = len(sequence) - 1 for element in reversed(sequence): yield (index, element) index -= 1 def append_leaves( new_line: Line, old_line: Line, leaves: list[Leaf], preformatted: bool = False ) -> None: """ Append leaves (taken from @old_line) to @new_line, making sure to fix the underlying Node structure where appropriate. All of the leaves in @leaves are duplicated. The duplicates are then appended to @new_line and used to replace their originals in the underlying Node structure. Any comments attached to the old leaves are reattached to the new leaves. Pre-conditions: set(@leaves) is a subset of set(@old_line.leaves). """ for old_leaf in leaves: new_leaf = Leaf(old_leaf.type, old_leaf.value) replace_child(old_leaf, new_leaf) new_line.append(new_leaf, preformatted=preformatted) for comment_leaf in old_line.comments_after(old_leaf): new_line.append(comment_leaf, preformatted=True) def is_line_short_enough(line: Line, *, mode: Mode, line_str: str = "") -> bool: """For non-multiline strings, return True if `line` is no longer than `line_length`. For multiline strings, looks at the context around `line` to determine if it should be inlined or split up. Uses the provided `line_str` rendering, if any, otherwise computes a new one. """ if not line_str: line_str = line_to_string(line) if Preview.multiline_string_handling not in mode: return ( str_width(line_str) <= mode.line_length and "\n" not in line_str # multiline strings and not line.contains_standalone_comments() ) if line.contains_standalone_comments(): return False if "\n" not in line_str: # No multiline strings (MLS) present return str_width(line_str) <= mode.line_length first, *_, last = line_str.split("\n") if str_width(first) > mode.line_length or str_width(last) > mode.line_length: return False # Traverse the AST to examine the context of the multiline string (MLS), # tracking aspects such as depth and comma existence, # to determine whether to split the MLS or keep it together. # Depth (which is based on the existing bracket_depth concept) # is needed to determine nesting level of the MLS. # Includes special case for trailing commas. commas: list[int] = [] # tracks number of commas per depth level multiline_string: Leaf | None = None # store the leaves that contain parts of the MLS multiline_string_contexts: list[LN] = [] max_level_to_update: int | float = math.inf # track the depth of the MLS for i, leaf in enumerate(line.leaves): if max_level_to_update == math.inf: had_comma: int | None = None if leaf.bracket_depth + 1 > len(commas): commas.append(0) elif leaf.bracket_depth + 1 < len(commas): had_comma = commas.pop() if ( had_comma is not None and multiline_string is not None and multiline_string.bracket_depth == leaf.bracket_depth + 1 ):
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
true
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/src/black/report.py
src/black/report.py
""" Summarize Black runs to users. """ from dataclasses import dataclass from enum import Enum from pathlib import Path from click import style from black.output import err, out class Changed(Enum): NO = 0 CACHED = 1 YES = 2 class NothingChanged(UserWarning): """Raised when reformatted code is the same as source.""" @dataclass class Report: """Provides a reformatting counter. Can be rendered with `str(report)`.""" check: bool = False diff: bool = False quiet: bool = False verbose: bool = False change_count: int = 0 same_count: int = 0 failure_count: int = 0 def done(self, src: Path, changed: Changed) -> None: """Increment the counter for successful reformatting. Write out a message.""" if changed is Changed.YES: reformatted = "would reformat" if self.check or self.diff else "reformatted" if self.verbose or not self.quiet: out(f"{reformatted} {src}") self.change_count += 1 else: if self.verbose: if changed is Changed.NO: msg = f"{src} already well formatted, good job." else: msg = f"{src} wasn't modified on disk since last run." out(msg, bold=False) self.same_count += 1 def failed(self, src: Path, message: str) -> None: """Increment the counter for failed reformatting. Write out a message.""" err(f"error: cannot format {src}: {message}") self.failure_count += 1 def path_ignored(self, path: Path, message: str) -> None: if self.verbose: out(f"{path} ignored: {message}", bold=False) @property def return_code(self) -> int: """Return the exit code that the app should use. This considers the current state of changed files and failures: - if there were any failures, return 123; - if any files were changed and --check is being used, return 1; - otherwise return 0. """ # According to http://tldp.org/LDP/abs/html/exitcodes.html starting with # 126 we have special return codes reserved by the shell. if self.failure_count: return 123 elif self.change_count and self.check: return 1 return 0 def __str__(self) -> str: """Render a color report of the current state. Use `click.unstyle` to remove colors. """ if self.check or self.diff: reformatted = "would be reformatted" unchanged = "would be left unchanged" failed = "would fail to reformat" else: reformatted = "reformatted" unchanged = "left unchanged" failed = "failed to reformat" report = [] if self.change_count: s = "s" if self.change_count > 1 else "" report.append( style(f"{self.change_count} file{s} ", bold=True, fg="blue") + style(f"{reformatted}", bold=True) ) if self.same_count: s = "s" if self.same_count > 1 else "" report.append(style(f"{self.same_count} file{s} ", fg="blue") + unchanged) if self.failure_count: s = "s" if self.failure_count > 1 else "" report.append(style(f"{self.failure_count} file{s} {failed}", fg="red")) return ", ".join(report) + "."
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/src/black/mode.py
src/black/mode.py
"""Data structures configuring Black behavior. Mostly around Python language feature support per version and Black configuration chosen by the user. """ from dataclasses import dataclass, field from enum import Enum, auto from hashlib import sha256 from operator import attrgetter from typing import Final from black.const import DEFAULT_LINE_LENGTH class TargetVersion(Enum): PY33 = 3 PY34 = 4 PY35 = 5 PY36 = 6 PY37 = 7 PY38 = 8 PY39 = 9 PY310 = 10 PY311 = 11 PY312 = 12 PY313 = 13 PY314 = 14 def pretty(self) -> str: assert self.name[:2] == "PY" return f"Python {self.name[2]}.{self.name[3:]}" class Feature(Enum): F_STRINGS = 2 NUMERIC_UNDERSCORES = 3 TRAILING_COMMA_IN_CALL = 4 TRAILING_COMMA_IN_DEF = 5 # The following two feature-flags are mutually exclusive, and exactly one should be # set for every version of python. ASYNC_IDENTIFIERS = 6 ASYNC_KEYWORDS = 7 ASSIGNMENT_EXPRESSIONS = 8 POS_ONLY_ARGUMENTS = 9 RELAXED_DECORATORS = 10 PATTERN_MATCHING = 11 UNPACKING_ON_FLOW = 12 ANN_ASSIGN_EXTENDED_RHS = 13 EXCEPT_STAR = 14 VARIADIC_GENERICS = 15 DEBUG_F_STRINGS = 16 PARENTHESIZED_CONTEXT_MANAGERS = 17 TYPE_PARAMS = 18 # FSTRING_PARSING = 19 # unused TYPE_PARAM_DEFAULTS = 20 UNPARENTHESIZED_EXCEPT_TYPES = 21 T_STRINGS = 22 FORCE_OPTIONAL_PARENTHESES = 50 # __future__ flags FUTURE_ANNOTATIONS = 51 FUTURE_FLAG_TO_FEATURE: Final = { "annotations": Feature.FUTURE_ANNOTATIONS, } VERSION_TO_FEATURES: dict[TargetVersion, set[Feature]] = { TargetVersion.PY33: {Feature.ASYNC_IDENTIFIERS}, TargetVersion.PY34: {Feature.ASYNC_IDENTIFIERS}, TargetVersion.PY35: {Feature.TRAILING_COMMA_IN_CALL, Feature.ASYNC_IDENTIFIERS}, TargetVersion.PY36: { Feature.F_STRINGS, Feature.NUMERIC_UNDERSCORES, Feature.TRAILING_COMMA_IN_CALL, Feature.TRAILING_COMMA_IN_DEF, Feature.ASYNC_IDENTIFIERS, }, TargetVersion.PY37: { Feature.F_STRINGS, Feature.NUMERIC_UNDERSCORES, Feature.TRAILING_COMMA_IN_CALL, Feature.TRAILING_COMMA_IN_DEF, Feature.ASYNC_KEYWORDS, Feature.FUTURE_ANNOTATIONS, }, TargetVersion.PY38: { Feature.F_STRINGS, Feature.DEBUG_F_STRINGS, Feature.NUMERIC_UNDERSCORES, Feature.TRAILING_COMMA_IN_CALL, Feature.TRAILING_COMMA_IN_DEF, Feature.ASYNC_KEYWORDS, Feature.FUTURE_ANNOTATIONS, Feature.ASSIGNMENT_EXPRESSIONS, Feature.POS_ONLY_ARGUMENTS, Feature.UNPACKING_ON_FLOW, Feature.ANN_ASSIGN_EXTENDED_RHS, }, TargetVersion.PY39: { Feature.F_STRINGS, Feature.DEBUG_F_STRINGS, Feature.NUMERIC_UNDERSCORES, Feature.TRAILING_COMMA_IN_CALL, Feature.TRAILING_COMMA_IN_DEF, Feature.ASYNC_KEYWORDS, Feature.FUTURE_ANNOTATIONS, Feature.ASSIGNMENT_EXPRESSIONS, Feature.RELAXED_DECORATORS, Feature.POS_ONLY_ARGUMENTS, Feature.UNPACKING_ON_FLOW, Feature.ANN_ASSIGN_EXTENDED_RHS, Feature.PARENTHESIZED_CONTEXT_MANAGERS, }, TargetVersion.PY310: { Feature.F_STRINGS, Feature.DEBUG_F_STRINGS, Feature.NUMERIC_UNDERSCORES, Feature.TRAILING_COMMA_IN_CALL, Feature.TRAILING_COMMA_IN_DEF, Feature.ASYNC_KEYWORDS, Feature.FUTURE_ANNOTATIONS, Feature.ASSIGNMENT_EXPRESSIONS, Feature.RELAXED_DECORATORS, Feature.POS_ONLY_ARGUMENTS, Feature.UNPACKING_ON_FLOW, Feature.ANN_ASSIGN_EXTENDED_RHS, Feature.PARENTHESIZED_CONTEXT_MANAGERS, Feature.PATTERN_MATCHING, }, TargetVersion.PY311: { Feature.F_STRINGS, Feature.DEBUG_F_STRINGS, Feature.NUMERIC_UNDERSCORES, Feature.TRAILING_COMMA_IN_CALL, Feature.TRAILING_COMMA_IN_DEF, Feature.ASYNC_KEYWORDS, Feature.FUTURE_ANNOTATIONS, Feature.ASSIGNMENT_EXPRESSIONS, Feature.RELAXED_DECORATORS, Feature.POS_ONLY_ARGUMENTS, Feature.UNPACKING_ON_FLOW, Feature.ANN_ASSIGN_EXTENDED_RHS, Feature.PARENTHESIZED_CONTEXT_MANAGERS, Feature.PATTERN_MATCHING, Feature.EXCEPT_STAR, Feature.VARIADIC_GENERICS, }, TargetVersion.PY312: { Feature.F_STRINGS, Feature.DEBUG_F_STRINGS, Feature.NUMERIC_UNDERSCORES, Feature.TRAILING_COMMA_IN_CALL, Feature.TRAILING_COMMA_IN_DEF, Feature.ASYNC_KEYWORDS, Feature.FUTURE_ANNOTATIONS, Feature.ASSIGNMENT_EXPRESSIONS, Feature.RELAXED_DECORATORS, Feature.POS_ONLY_ARGUMENTS, Feature.UNPACKING_ON_FLOW, Feature.ANN_ASSIGN_EXTENDED_RHS, Feature.PARENTHESIZED_CONTEXT_MANAGERS, Feature.PATTERN_MATCHING, Feature.EXCEPT_STAR, Feature.VARIADIC_GENERICS, Feature.TYPE_PARAMS, }, TargetVersion.PY313: { Feature.F_STRINGS, Feature.DEBUG_F_STRINGS, Feature.NUMERIC_UNDERSCORES, Feature.TRAILING_COMMA_IN_CALL, Feature.TRAILING_COMMA_IN_DEF, Feature.ASYNC_KEYWORDS, Feature.FUTURE_ANNOTATIONS, Feature.ASSIGNMENT_EXPRESSIONS, Feature.RELAXED_DECORATORS, Feature.POS_ONLY_ARGUMENTS, Feature.UNPACKING_ON_FLOW, Feature.ANN_ASSIGN_EXTENDED_RHS, Feature.PARENTHESIZED_CONTEXT_MANAGERS, Feature.PATTERN_MATCHING, Feature.EXCEPT_STAR, Feature.VARIADIC_GENERICS, Feature.TYPE_PARAMS, Feature.TYPE_PARAM_DEFAULTS, }, TargetVersion.PY314: { Feature.F_STRINGS, Feature.DEBUG_F_STRINGS, Feature.NUMERIC_UNDERSCORES, Feature.TRAILING_COMMA_IN_CALL, Feature.TRAILING_COMMA_IN_DEF, Feature.ASYNC_KEYWORDS, Feature.FUTURE_ANNOTATIONS, Feature.ASSIGNMENT_EXPRESSIONS, Feature.RELAXED_DECORATORS, Feature.POS_ONLY_ARGUMENTS, Feature.UNPACKING_ON_FLOW, Feature.ANN_ASSIGN_EXTENDED_RHS, Feature.PARENTHESIZED_CONTEXT_MANAGERS, Feature.PATTERN_MATCHING, Feature.EXCEPT_STAR, Feature.VARIADIC_GENERICS, Feature.TYPE_PARAMS, Feature.TYPE_PARAM_DEFAULTS, Feature.UNPARENTHESIZED_EXCEPT_TYPES, Feature.T_STRINGS, }, } def supports_feature(target_versions: set[TargetVersion], feature: Feature) -> bool: if not target_versions: raise ValueError("target_versions must not be empty") return all(feature in VERSION_TO_FEATURES[version] for version in target_versions) class Preview(Enum): """Individual preview style features.""" # NOTE: string_processing requires wrap_long_dict_values_in_parens # for https://github.com/psf/black/issues/3117 to be fixed. string_processing = auto() hug_parens_with_braces_and_square_brackets = auto() wrap_long_dict_values_in_parens = auto() multiline_string_handling = auto() always_one_newline_after_import = auto() fix_fmt_skip_in_one_liners = auto() standardize_type_comments = auto() wrap_comprehension_in = auto() # Remove parentheses around multiple exception types in except and # except* without as. See PEP 758 for details. remove_parens_around_except_types = auto() normalize_cr_newlines = auto() fix_module_docstring_detection = auto() fix_type_expansion_split = auto() remove_parens_from_assignment_lhs = auto() UNSTABLE_FEATURES: set[Preview] = { # Many issues, see summary in https://github.com/psf/black/issues/4042 Preview.string_processing, # See issue #4036 (crash), #4098, #4099 (proposed tweaks) Preview.hug_parens_with_braces_and_square_brackets, } class Deprecated(UserWarning): """Visible deprecation warning.""" _MAX_CACHE_KEY_PART_LENGTH: Final = 32 @dataclass class Mode: target_versions: set[TargetVersion] = field(default_factory=set) line_length: int = DEFAULT_LINE_LENGTH string_normalization: bool = True is_pyi: bool = False is_ipynb: bool = False skip_source_first_line: bool = False magic_trailing_comma: bool = True python_cell_magics: set[str] = field(default_factory=set) preview: bool = False unstable: bool = False enabled_features: set[Preview] = field(default_factory=set) def __contains__(self, feature: Preview) -> bool: """ Provide `Preview.FEATURE in Mode` syntax that mirrors the ``preview`` flag. In unstable mode, all features are enabled. In preview mode, all features except those in UNSTABLE_FEATURES are enabled. Any features in `self.enabled_features` are also enabled. """ if self.unstable: return True if feature in self.enabled_features: return True return self.preview and feature not in UNSTABLE_FEATURES def get_cache_key(self) -> str: if self.target_versions: version_str = ",".join( str(version.value) for version in sorted(self.target_versions, key=attrgetter("value")) ) else: version_str = "-" if len(version_str) > _MAX_CACHE_KEY_PART_LENGTH: version_str = sha256(version_str.encode()).hexdigest()[ :_MAX_CACHE_KEY_PART_LENGTH ] features_and_magics = ( ",".join(sorted(f.name for f in self.enabled_features)) + "@" + ",".join(sorted(self.python_cell_magics)) ) if len(features_and_magics) > _MAX_CACHE_KEY_PART_LENGTH: features_and_magics = sha256(features_and_magics.encode()).hexdigest()[ :_MAX_CACHE_KEY_PART_LENGTH ] parts = [ version_str, str(self.line_length), str(int(self.string_normalization)), str(int(self.is_pyi)), str(int(self.is_ipynb)), str(int(self.skip_source_first_line)), str(int(self.magic_trailing_comma)), str(int(self.preview)), str(int(self.unstable)), features_and_magics, ] return ".".join(parts) def __hash__(self) -> int: return hash(( frozenset(self.target_versions), self.line_length, self.string_normalization, self.is_pyi, self.is_ipynb, self.skip_source_first_line, self.magic_trailing_comma, frozenset(self.python_cell_magics), self.preview, self.unstable, frozenset(self.enabled_features), ))
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/src/black/trans.py
src/black/trans.py
""" String transformers that can split and merge strings. """ import re from abc import ABC, abstractmethod from collections import defaultdict from collections.abc import Callable, Collection, Iterable, Iterator, Sequence from dataclasses import dataclass from typing import Any, ClassVar, Final, Literal, TypeVar, Union from mypy_extensions import trait from black.comments import contains_pragma_comment from black.lines import Line, append_leaves from black.mode import Feature, Mode from black.nodes import ( CLOSING_BRACKETS, OPENING_BRACKETS, STANDALONE_COMMENT, is_empty_lpar, is_empty_par, is_empty_rpar, is_part_of_annotation, parent_type, replace_child, syms, ) from black.rusty import Err, Ok, Result from black.strings import ( assert_is_leaf_string, count_chars_in_width, get_string_prefix, has_triple_quotes, normalize_string_quotes, str_width, ) from blib2to3.pgen2 import token from blib2to3.pytree import Leaf, Node class CannotTransform(Exception): """Base class for errors raised by Transformers.""" # types T = TypeVar("T") LN = Union[Leaf, Node] Transformer = Callable[[Line, Collection[Feature], Mode], Iterator[Line]] Index = int NodeType = int ParserState = int StringID = int TResult = Result[T, CannotTransform] # (T)ransform Result TMatchResult = TResult[list[Index]] SPLIT_SAFE_CHARS = frozenset(["\u3001", "\u3002", "\uff0c"]) # East Asian stops def TErr(err_msg: str) -> Err[CannotTransform]: """(T)ransform Err Convenience function used when working with the TResult type. """ cant_transform = CannotTransform(err_msg) return Err(cant_transform) def hug_power_op( line: Line, features: Collection[Feature], mode: Mode ) -> Iterator[Line]: """A transformer which normalizes spacing around power operators.""" # Performance optimization to avoid unnecessary Leaf clones and other ops. for leaf in line.leaves: if leaf.type == token.DOUBLESTAR: break else: raise CannotTransform("No doublestar token was found in the line.") def is_simple_lookup(index: int, kind: Literal[1, -1]) -> bool: # Brackets and parentheses indicate calls, subscripts, etc. ... # basically stuff that doesn't count as "simple". Only a NAME lookup # or dotted lookup (eg. NAME.NAME) is OK. if kind == -1: return handle_is_simple_look_up_prev(line, index, {token.RPAR, token.RSQB}) else: return handle_is_simple_lookup_forward( line, index, {token.LPAR, token.LSQB} ) def is_simple_operand(index: int, kind: Literal[1, -1]) -> bool: # An operand is considered "simple" if's a NAME, a numeric CONSTANT, a simple # lookup (see above), with or without a preceding unary operator. start = line.leaves[index] if start.type in {token.NAME, token.NUMBER}: return is_simple_lookup(index, kind) if start.type in {token.PLUS, token.MINUS, token.TILDE}: if line.leaves[index + 1].type in {token.NAME, token.NUMBER}: # kind is always one as bases with a preceding unary op will be checked # for simplicity starting from the next token (so it'll hit the check # above). return is_simple_lookup(index + 1, kind=1) return False new_line = line.clone() should_hug = False for idx, leaf in enumerate(line.leaves): new_leaf = leaf.clone() if should_hug: new_leaf.prefix = "" should_hug = False should_hug = ( (0 < idx < len(line.leaves) - 1) and leaf.type == token.DOUBLESTAR and is_simple_operand(idx - 1, kind=-1) and line.leaves[idx - 1].value != "lambda" and is_simple_operand(idx + 1, kind=1) ) if should_hug: new_leaf.prefix = "" # We have to be careful to make a new line properly: # - bracket related metadata must be maintained (handled by Line.append) # - comments need to copied over, updating the leaf IDs they're attached to new_line.append(new_leaf, preformatted=True) for comment_leaf in line.comments_after(leaf): new_line.append(comment_leaf, preformatted=True) yield new_line def handle_is_simple_look_up_prev(line: Line, index: int, disallowed: set[int]) -> bool: """ Handling the determination of is_simple_lookup for the lines prior to the doublestar token. This is required because of the need to isolate the chained expression to determine the bracket or parenthesis belong to the single expression. """ contains_disallowed = False chain = [] while 0 <= index < len(line.leaves): current = line.leaves[index] chain.append(current) if not contains_disallowed and current.type in disallowed: contains_disallowed = True if not is_expression_chained(chain): return not contains_disallowed index -= 1 return True def handle_is_simple_lookup_forward( line: Line, index: int, disallowed: set[int] ) -> bool: """ Handling decision is_simple_lookup for the lines behind the doublestar token. This function is simplified to keep consistent with the prior logic and the forward case are more straightforward and do not need to care about chained expressions. """ while 0 <= index < len(line.leaves): current = line.leaves[index] if current.type in disallowed: return False if current.type not in {token.NAME, token.DOT} or ( current.type == token.NAME and current.value == "for" ): # If the current token isn't disallowed, we'll assume this is simple as # only the disallowed tokens are semantically attached to this lookup # expression we're checking. Also, stop early if we hit the 'for' bit # of a comprehension. return True index += 1 return True def is_expression_chained(chained_leaves: list[Leaf]) -> bool: """ Function to determine if the variable is a chained call. (e.g., foo.lookup, foo().lookup, (foo.lookup())) will be recognized as chained call) """ if len(chained_leaves) < 2: return True current_leaf = chained_leaves[-1] past_leaf = chained_leaves[-2] if past_leaf.type == token.NAME: return current_leaf.type in {token.DOT} elif past_leaf.type in {token.RPAR, token.RSQB}: return current_leaf.type in {token.RSQB, token.RPAR} elif past_leaf.type in {token.LPAR, token.LSQB}: return current_leaf.type in {token.NAME, token.LPAR, token.LSQB} else: return False class StringTransformer(ABC): """ An implementation of the Transformer protocol that relies on its subclasses overriding the template methods `do_match(...)` and `do_transform(...)`. This Transformer works exclusively on strings (for example, by merging or splitting them). The following sections can be found among the docstrings of each concrete StringTransformer subclass. Requirements: Which requirements must be met of the given Line for this StringTransformer to be applied? Transformations: If the given Line meets all of the above requirements, which string transformations can you expect to be applied to it by this StringTransformer? Collaborations: What contractual agreements does this StringTransformer have with other StringTransfomers? Such collaborations should be eliminated/minimized as much as possible. """ __name__: Final = "StringTransformer" # Ideally this would be a dataclass, but unfortunately mypyc breaks when used with # `abc.ABC`. def __init__(self, line_length: int, normalize_strings: bool) -> None: self.line_length = line_length self.normalize_strings = normalize_strings @abstractmethod def do_match(self, line: Line) -> TMatchResult: """ Returns: * Ok(string_indices) such that for each index, `line.leaves[index]` is our target string if a match was able to be made. For transformers that don't result in more lines (e.g. StringMerger, StringParenStripper), multiple matches and transforms are done at once to reduce the complexity. OR * Err(CannotTransform), if no match could be made. """ @abstractmethod def do_transform( self, line: Line, string_indices: list[int] ) -> Iterator[TResult[Line]]: """ Yields: * Ok(new_line) where new_line is the new transformed line. OR * Err(CannotTransform) if the transformation failed for some reason. The `do_match(...)` template method should usually be used to reject the form of the given Line, but in some cases it is difficult to know whether or not a Line meets the StringTransformer's requirements until the transformation is already midway. Side Effects: This method should NOT mutate @line directly, but it MAY mutate the Line's underlying Node structure. (WARNING: If the underlying Node structure IS altered, then this method should NOT be allowed to yield an CannotTransform after that point.) """ def __call__( self, line: Line, _features: Collection[Feature], _mode: Mode ) -> Iterator[Line]: """ StringTransformer instances have a call signature that mirrors that of the Transformer type. Raises: CannotTransform(...) if the concrete StringTransformer class is unable to transform @line. """ # Optimization to avoid calling `self.do_match(...)` when the line does # not contain any string. if not any(leaf.type == token.STRING for leaf in line.leaves): raise CannotTransform("There are no strings in this line.") match_result = self.do_match(line) if isinstance(match_result, Err): cant_transform = match_result.err() raise CannotTransform( f"The string transformer {self.__class__.__name__} does not recognize" " this line as one that it can transform." ) from cant_transform string_indices = match_result.ok() for line_result in self.do_transform(line, string_indices): if isinstance(line_result, Err): cant_transform = line_result.err() raise CannotTransform( "StringTransformer failed while attempting to transform string." ) from cant_transform line = line_result.ok() yield line @dataclass class CustomSplit: """A custom (i.e. manual) string split. A single CustomSplit instance represents a single substring. Examples: Consider the following string: ``` "Hi there friend." " This is a custom" f" string {split}." ``` This string will correspond to the following three CustomSplit instances: ``` CustomSplit(False, 16) CustomSplit(False, 17) CustomSplit(True, 16) ``` """ has_prefix: bool break_idx: int CustomSplitMapKey = tuple[StringID, str] @trait class CustomSplitMapMixin: """ This mixin class is used to map merged strings to a sequence of CustomSplits, which will then be used to re-split the strings iff none of the resultant substrings go over the configured max line length. """ _CUSTOM_SPLIT_MAP: ClassVar[dict[CustomSplitMapKey, tuple[CustomSplit, ...]]] = ( defaultdict(tuple) ) @staticmethod def _get_key(string: str) -> CustomSplitMapKey: """ Returns: A unique identifier that is used internally to map @string to a group of custom splits. """ return (id(string), string) def add_custom_splits( self, string: str, custom_splits: Iterable[CustomSplit] ) -> None: """Custom Split Map Setter Method Side Effects: Adds a mapping from @string to the custom splits @custom_splits. """ key = self._get_key(string) self._CUSTOM_SPLIT_MAP[key] = tuple(custom_splits) def pop_custom_splits(self, string: str) -> list[CustomSplit]: """Custom Split Map Getter Method Returns: * A list of the custom splits that are mapped to @string, if any exist. OR * [], otherwise. Side Effects: Deletes the mapping between @string and its associated custom splits (which are returned to the caller). """ key = self._get_key(string) custom_splits = self._CUSTOM_SPLIT_MAP[key] del self._CUSTOM_SPLIT_MAP[key] return list(custom_splits) def has_custom_splits(self, string: str) -> bool: """ Returns: True iff @string is associated with a set of custom splits. """ key = self._get_key(string) return key in self._CUSTOM_SPLIT_MAP class StringMerger(StringTransformer, CustomSplitMapMixin): """StringTransformer that merges strings together. Requirements: (A) The line contains adjacent strings such that ALL of the validation checks listed in StringMerger._validate_msg(...)'s docstring pass. OR (B) The line contains a string which uses line continuation backslashes. Transformations: Depending on which of the two requirements above where met, either: (A) The string group associated with the target string is merged. OR (B) All line-continuation backslashes are removed from the target string. Collaborations: StringMerger provides custom split information to StringSplitter. """ def do_match(self, line: Line) -> TMatchResult: LL = line.leaves is_valid_index = is_valid_index_factory(LL) string_indices = [] idx = 0 while is_valid_index(idx): leaf = LL[idx] if ( leaf.type == token.STRING and is_valid_index(idx + 1) and LL[idx + 1].type == token.STRING ): # Let's check if the string group contains an inline comment # If we have a comment inline, we don't merge the strings contains_comment = False i = idx while is_valid_index(i): if LL[i].type != token.STRING: break if line.comments_after(LL[i]): contains_comment = True break i += 1 if not contains_comment and not is_part_of_annotation(leaf): string_indices.append(idx) # Advance to the next non-STRING leaf. idx += 2 while is_valid_index(idx) and LL[idx].type == token.STRING: idx += 1 elif leaf.type == token.STRING and "\\\n" in leaf.value: string_indices.append(idx) # Advance to the next non-STRING leaf. idx += 1 while is_valid_index(idx) and LL[idx].type == token.STRING: idx += 1 else: idx += 1 if string_indices: return Ok(string_indices) else: return TErr("This line has no strings that need merging.") def do_transform( self, line: Line, string_indices: list[int] ) -> Iterator[TResult[Line]]: new_line = line rblc_result = self._remove_backslash_line_continuation_chars( new_line, string_indices ) if isinstance(rblc_result, Ok): new_line = rblc_result.ok() msg_result = self._merge_string_group(new_line, string_indices) if isinstance(msg_result, Ok): new_line = msg_result.ok() if isinstance(rblc_result, Err) and isinstance(msg_result, Err): msg_cant_transform = msg_result.err() rblc_cant_transform = rblc_result.err() cant_transform = CannotTransform( "StringMerger failed to merge any strings in this line." ) # Chain the errors together using `__cause__`. msg_cant_transform.__cause__ = rblc_cant_transform cant_transform.__cause__ = msg_cant_transform yield Err(cant_transform) else: yield Ok(new_line) @staticmethod def _remove_backslash_line_continuation_chars( line: Line, string_indices: list[int] ) -> TResult[Line]: """ Merge strings that were split across multiple lines using line-continuation backslashes. Returns: Ok(new_line), if @line contains backslash line-continuation characters. OR Err(CannotTransform), otherwise. """ LL = line.leaves indices_to_transform = [] for string_idx in string_indices: string_leaf = LL[string_idx] if ( string_leaf.type == token.STRING and "\\\n" in string_leaf.value and not has_triple_quotes(string_leaf.value) ): indices_to_transform.append(string_idx) if not indices_to_transform: return TErr( "Found no string leaves that contain backslash line continuation" " characters." ) new_line = line.clone() new_line.comments = line.comments.copy() append_leaves(new_line, line, LL) for string_idx in indices_to_transform: new_string_leaf = new_line.leaves[string_idx] new_string_leaf.value = new_string_leaf.value.replace("\\\n", "") return Ok(new_line) def _merge_string_group( self, line: Line, string_indices: list[int] ) -> TResult[Line]: """ Merges string groups (i.e. set of adjacent strings). Each index from `string_indices` designates one string group's first leaf in `line.leaves`. Returns: Ok(new_line), if ALL of the validation checks found in _validate_msg(...) pass. OR Err(CannotTransform), otherwise. """ LL = line.leaves is_valid_index = is_valid_index_factory(LL) # A dict of {string_idx: tuple[num_of_strings, string_leaf]}. merged_string_idx_dict: dict[int, tuple[int, Leaf]] = {} for string_idx in string_indices: vresult = self._validate_msg(line, string_idx) if isinstance(vresult, Err): continue merged_string_idx_dict[string_idx] = self._merge_one_string_group( LL, string_idx, is_valid_index ) if not merged_string_idx_dict: return TErr("No string group is merged") # Build the final line ('new_line') that this method will later return. new_line = line.clone() previous_merged_string_idx = -1 previous_merged_num_of_strings = -1 for i, leaf in enumerate(LL): if i in merged_string_idx_dict: previous_merged_string_idx = i previous_merged_num_of_strings, string_leaf = merged_string_idx_dict[i] new_line.append(string_leaf) if ( previous_merged_string_idx <= i < previous_merged_string_idx + previous_merged_num_of_strings ): for comment_leaf in line.comments_after(leaf): new_line.append(comment_leaf, preformatted=True) continue append_leaves(new_line, line, [leaf]) return Ok(new_line) def _merge_one_string_group( self, LL: list[Leaf], string_idx: int, is_valid_index: Callable[[int], bool] ) -> tuple[int, Leaf]: """ Merges one string group where the first string in the group is `LL[string_idx]`. Returns: A tuple of `(num_of_strings, leaf)` where `num_of_strings` is the number of strings merged and `leaf` is the newly merged string to be replaced in the new line. """ # If the string group is wrapped inside an Atom node, we must make sure # to later replace that Atom with our new (merged) string leaf. atom_node = LL[string_idx].parent # We will place BREAK_MARK in between every two substrings that we # merge. We will then later go through our final result and use the # various instances of BREAK_MARK we find to add the right values to # the custom split map. BREAK_MARK = "@@@@@ BLACK BREAKPOINT MARKER @@@@@" QUOTE = LL[string_idx].value[-1] def make_naked(string: str, string_prefix: str) -> str: """Strip @string (i.e. make it a "naked" string) Pre-conditions: * assert_is_leaf_string(@string) Returns: A string that is identical to @string except that @string_prefix has been stripped, the surrounding QUOTE characters have been removed, and any remaining QUOTE characters have been escaped. """ assert_is_leaf_string(string) if "f" in string_prefix: f_expressions = [ string[span[0] + 1 : span[1] - 1] # +-1 to get rid of curly braces for span in iter_fexpr_spans(string) ] debug_expressions_contain_visible_quotes = any( re.search(r".*[\'\"].*(?<![!:=])={1}(?!=)(?![^\s:])", expression) for expression in f_expressions ) if not debug_expressions_contain_visible_quotes: # We don't want to toggle visible quotes in debug f-strings, as # that would modify the AST string = _toggle_fexpr_quotes(string, QUOTE) # After quotes toggling, quotes in expressions won't be escaped # because quotes can't be reused in f-strings. So we can simply # let the escaping logic below run without knowing f-string # expressions. RE_EVEN_BACKSLASHES = r"(?:(?<!\\)(?:\\\\)*)" naked_string = string[len(string_prefix) + 1 : -1] naked_string = re.sub( "(" + RE_EVEN_BACKSLASHES + ")" + QUOTE, r"\1\\" + QUOTE, naked_string ) return naked_string # Holds the CustomSplit objects that will later be added to the custom # split map. custom_splits = [] # Temporary storage for the 'has_prefix' part of the CustomSplit objects. prefix_tracker = [] # Sets the 'prefix' variable. This is the prefix that the final merged # string will have. next_str_idx = string_idx prefix = "" while ( not prefix and is_valid_index(next_str_idx) and LL[next_str_idx].type == token.STRING ): prefix = get_string_prefix(LL[next_str_idx].value).lower() next_str_idx += 1 # The next loop merges the string group. The final string will be # contained in 'S'. # # The following convenience variables are used: # # S: string # NS: naked string # SS: next string # NSS: naked next string S = "" NS = "" num_of_strings = 0 next_str_idx = string_idx while is_valid_index(next_str_idx) and LL[next_str_idx].type == token.STRING: num_of_strings += 1 SS = LL[next_str_idx].value next_prefix = get_string_prefix(SS).lower() # If this is an f-string group but this substring is not prefixed # with 'f'... if "f" in prefix and "f" not in next_prefix: # Then we must escape any braces contained in this substring. SS = re.sub(r"(\{|\})", r"\1\1", SS) NSS = make_naked(SS, next_prefix) has_prefix = bool(next_prefix) prefix_tracker.append(has_prefix) S = prefix + QUOTE + NS + NSS + BREAK_MARK + QUOTE NS = make_naked(S, prefix) next_str_idx += 1 # Take a note on the index of the non-STRING leaf. non_string_idx = next_str_idx S_leaf = Leaf(token.STRING, S) if self.normalize_strings: S_leaf.value = normalize_string_quotes(S_leaf.value) # Fill the 'custom_splits' list with the appropriate CustomSplit objects. temp_string = S_leaf.value[len(prefix) + 1 : -1] for has_prefix in prefix_tracker: mark_idx = temp_string.find(BREAK_MARK) assert ( mark_idx >= 0 ), "Logic error while filling the custom string breakpoint cache." temp_string = temp_string[mark_idx + len(BREAK_MARK) :] breakpoint_idx = mark_idx + (len(prefix) if has_prefix else 0) + 1 custom_splits.append(CustomSplit(has_prefix, breakpoint_idx)) string_leaf = Leaf(token.STRING, S_leaf.value.replace(BREAK_MARK, "")) if atom_node is not None: # If not all children of the atom node are merged (this can happen # when there is a standalone comment in the middle) ... if non_string_idx - string_idx < len(atom_node.children): # We need to replace the old STRING leaves with the new string leaf. first_child_idx = LL[string_idx].remove() for idx in range(string_idx + 1, non_string_idx): LL[idx].remove() if first_child_idx is not None: atom_node.insert_child(first_child_idx, string_leaf) else: # Else replace the atom node with the new string leaf. replace_child(atom_node, string_leaf) self.add_custom_splits(string_leaf.value, custom_splits) return num_of_strings, string_leaf @staticmethod def _validate_msg(line: Line, string_idx: int) -> TResult[None]: """Validate (M)erge (S)tring (G)roup Transform-time string validation logic for _merge_string_group(...). Returns: * Ok(None), if ALL validation checks (listed below) pass. OR * Err(CannotTransform), if any of the following are true: - The target string group does not contain ANY stand-alone comments. - The target string is not in a string group (i.e. it has no adjacent strings). - The string group has more than one inline comment. - The string group has an inline comment that appears to be a pragma. - The set of all string prefixes in the string group is of length greater than one and is not equal to {"", "f"}. - The string group consists of raw strings. - The string group would merge f-strings with different quote types and internal quotes. - The string group is stringified type annotations. We don't want to process stringified type annotations since pyright doesn't support them spanning multiple string values. (NOTE: mypy, pytype, pyre do support them, so we can change if pyright also gains support in the future. See https://github.com/microsoft/pyright/issues/4359.) """ # We first check for "inner" stand-alone comments (i.e. stand-alone # comments that have a string leaf before them AND after them). for inc in [1, -1]: i = string_idx found_sa_comment = False is_valid_index = is_valid_index_factory(line.leaves) while is_valid_index(i) and line.leaves[i].type in [ token.STRING, STANDALONE_COMMENT, ]: if line.leaves[i].type == STANDALONE_COMMENT: found_sa_comment = True elif found_sa_comment: return TErr( "StringMerger does NOT merge string groups which contain " "stand-alone comments." ) i += inc QUOTE = line.leaves[string_idx].value[-1] num_of_inline_string_comments = 0 set_of_prefixes = set() num_of_strings = 0 for leaf in line.leaves[string_idx:]: if leaf.type != token.STRING: # If the string group is trailed by a comma, we count the # comments trailing the comma to be one of the string group's # comments. if leaf.type == token.COMMA and id(leaf) in line.comments: num_of_inline_string_comments += 1 break if has_triple_quotes(leaf.value): return TErr("StringMerger does NOT merge multiline strings.") num_of_strings += 1 prefix = get_string_prefix(leaf.value).lower() if "r" in prefix: return TErr("StringMerger does NOT merge raw strings.") set_of_prefixes.add(prefix) if ( "f" in prefix and leaf.value[-1] != QUOTE and ( "'" in leaf.value[len(prefix) + 1 : -1] or '"' in leaf.value[len(prefix) + 1 : -1] ) ): return TErr( "StringMerger does NOT merge f-strings with different quote types" " and internal quotes." ) if id(leaf) in line.comments: num_of_inline_string_comments += 1 if contains_pragma_comment(line.comments[id(leaf)]): return TErr("Cannot merge strings which have pragma comments.") if num_of_strings < 2: return TErr( f"Not enough strings to merge (num_of_strings={num_of_strings})." ) if num_of_inline_string_comments > 1: return TErr( f"Too many inline string comments ({num_of_inline_string_comments})." ) if len(set_of_prefixes) > 1 and set_of_prefixes != {"", "f"}: return TErr(f"Too many different prefixes ({set_of_prefixes}).") return Ok(None) class StringParenStripper(StringTransformer): """StringTransformer that strips surrounding parentheses from strings. Requirements: The line contains a string which is surrounded by parentheses and: - The target string is NOT the only argument to a function call. - The target string is NOT a "pointless" string. - The target string is NOT a dictionary value. - If the target string contains a PERCENT, the brackets are not preceded or followed by an operator with higher precedence than PERCENT. Transformations: The parentheses mentioned in the 'Requirements' section are stripped. Collaborations: StringParenStripper has its own inherent usefulness, but it is also relied on to clean up the parentheses created by StringParenWrapper (in the event that they are no longer needed). """ def do_match(self, line: Line) -> TMatchResult: LL = line.leaves is_valid_index = is_valid_index_factory(LL) string_indices = [] idx = -1 while True: idx += 1 if idx >= len(LL): break leaf = LL[idx] # Should be a string... if leaf.type != token.STRING: continue # If this is a "pointless" string... if ( leaf.parent and leaf.parent.parent and leaf.parent.parent.type == syms.simple_stmt ): continue
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
true
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/src/black/debug.py
src/black/debug.py
from collections.abc import Iterator from dataclasses import dataclass, field from typing import Any, TypeVar, Union from black.nodes import Visitor from black.output import out from black.parsing import lib2to3_parse from blib2to3.pgen2 import token from blib2to3.pytree import Leaf, Node, type_repr LN = Union[Leaf, Node] T = TypeVar("T") @dataclass class DebugVisitor(Visitor[T]): tree_depth: int = 0 list_output: list[str] = field(default_factory=list) print_output: bool = True def out(self, message: str, *args: Any, **kwargs: Any) -> None: self.list_output.append(message) if self.print_output: out(message, *args, **kwargs) def visit_default(self, node: LN) -> Iterator[T]: indent = " " * (2 * self.tree_depth) if isinstance(node, Node): _type = type_repr(node.type) self.out(f"{indent}{_type}", fg="yellow") self.tree_depth += 1 for child in node.children: yield from self.visit(child) self.tree_depth -= 1 self.out(f"{indent}/{_type}", fg="yellow", bold=False) else: _type = token.tok_name.get(node.type, str(node.type)) self.out(f"{indent}{_type}", fg="blue", nl=False) if node.prefix: # We don't have to handle prefixes for `Node` objects since # that delegates to the first child anyway. self.out(f" {node.prefix!r}", fg="green", bold=False, nl=False) self.out(f" {node.value!r}", fg="blue", bold=False) @classmethod def show(cls, code: str | Leaf | Node) -> None: """Pretty-print the lib2to3 AST of a given string of `code`. Convenience method for debugging. """ v: DebugVisitor[None] = DebugVisitor() if isinstance(code, str): code = lib2to3_parse(code) list(v.visit(code))
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/src/black/numerics.py
src/black/numerics.py
""" Formatting numeric literals. """ from blib2to3.pytree import Leaf def format_hex(text: str) -> str: """ Formats a hexadecimal string like "0x12B3" """ before, after = text[:2], text[2:] return f"{before}{after.upper()}" def format_scientific_notation(text: str) -> str: """Formats a numeric string utilizing scientific notation""" before, after = text.split("e") sign = "" if after.startswith("-"): after = after[1:] sign = "-" elif after.startswith("+"): after = after[1:] before = format_float_or_int_string(before) return f"{before}e{sign}{after}" def format_complex_number(text: str) -> str: """Formats a complex string like `10j`""" number = text[:-1] suffix = text[-1] return f"{format_float_or_int_string(number)}{suffix}" def format_float_or_int_string(text: str) -> str: """Formats a float string like "1.0".""" if "." not in text: return text before, after = text.split(".") return f"{before or 0}.{after or 0}" def normalize_numeric_literal(leaf: Leaf) -> None: """Normalizes numeric (float, int, and complex) literals. All letters used in the representation are normalized to lowercase.""" text = leaf.value.lower() if text.startswith(("0o", "0b")): # Leave octal and binary literals alone. pass elif text.startswith("0x"): text = format_hex(text) elif "e" in text: text = format_scientific_notation(text) elif text.endswith("j"): text = format_complex_number(text) else: text = format_float_or_int_string(text) leaf.value = text
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/src/black/output.py
src/black/output.py
"""Nice output for Black. The double calls are for patching purposes in tests. """ import json import re import tempfile from typing import Any from click import echo, style from mypy_extensions import mypyc_attr @mypyc_attr(patchable=True) def _out(message: str | None = None, nl: bool = True, **styles: Any) -> None: if message is not None: if "bold" not in styles: styles["bold"] = True message = style(message, **styles) echo(message, nl=nl, err=True) @mypyc_attr(patchable=True) def _err(message: str | None = None, nl: bool = True, **styles: Any) -> None: if message is not None: if "fg" not in styles: styles["fg"] = "red" message = style(message, **styles) echo(message, nl=nl, err=True) @mypyc_attr(patchable=True) def out(message: str | None = None, nl: bool = True, **styles: Any) -> None: _out(message, nl=nl, **styles) def err(message: str | None = None, nl: bool = True, **styles: Any) -> None: _err(message, nl=nl, **styles) def ipynb_diff(a: str, b: str, a_name: str, b_name: str) -> str: """Return a unified diff string between each cell in notebooks `a` and `b`.""" a_nb = json.loads(a) b_nb = json.loads(b) diff_lines = [ diff( "".join(a_nb["cells"][cell_number]["source"]) + "\n", "".join(b_nb["cells"][cell_number]["source"]) + "\n", f"{a_name}:cell_{cell_number}", f"{b_name}:cell_{cell_number}", ) for cell_number, cell in enumerate(a_nb["cells"]) if cell["cell_type"] == "code" ] return "".join(diff_lines) _line_pattern = re.compile(r"(.*?(?:\r\n|\n|\r|$))") def _splitlines_no_ff(source: str) -> list[str]: """Split a string into lines ignoring form feed and other chars. This mimics how the Python parser splits source code. A simplified version of the function with the same name in Lib/ast.py """ result = [match[0] for match in _line_pattern.finditer(source)] if result[-1] == "": result.pop(-1) return result def diff(a: str, b: str, a_name: str, b_name: str) -> str: """Return a unified diff string between strings `a` and `b`.""" import difflib a_lines = _splitlines_no_ff(a) b_lines = _splitlines_no_ff(b) diff_lines = [] for line in difflib.unified_diff( a_lines, b_lines, fromfile=a_name, tofile=b_name, n=5 ): # Work around https://bugs.python.org/issue2142 # See: # https://www.gnu.org/software/diffutils/manual/html_node/Incomplete-Lines.html if line[-1] == "\n": diff_lines.append(line) else: diff_lines.append(line + "\n") diff_lines.append("\\ No newline at end of file\n") return "".join(diff_lines) def color_diff(contents: str) -> str: """Inject the ANSI color codes to the diff.""" lines = contents.split("\n") for i, line in enumerate(lines): if line.startswith("+++") or line.startswith("---"): line = "\033[1m" + line + "\033[0m" # bold, reset elif line.startswith("@@"): line = "\033[36m" + line + "\033[0m" # cyan, reset elif line.startswith("+"): line = "\033[32m" + line + "\033[0m" # green, reset elif line.startswith("-"): line = "\033[31m" + line + "\033[0m" # red, reset lines[i] = line return "\n".join(lines) @mypyc_attr(patchable=True) def dump_to_file(*output: str, ensure_final_newline: bool = True) -> str: """Dump `output` to a temporary file. Return path to the file.""" with tempfile.NamedTemporaryFile( mode="w", prefix="blk_", suffix=".log", delete=False, encoding="utf8" ) as f: for lines in output: f.write(lines) if ensure_final_newline and lines and lines[-1] != "\n": f.write("\n") return f.name
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/src/black/schema.py
src/black/schema.py
import importlib.resources import json from typing import Any def get_schema(tool_name: str = "black") -> Any: """Get the stored complete schema for black's settings.""" assert tool_name == "black", "Only black is supported." pkg = "black.resources" fname = "black.schema.json" schema = importlib.resources.files(pkg).joinpath(fname) with schema.open(encoding="utf-8") as f: return json.load(f)
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/src/black/rusty.py
src/black/rusty.py
"""An error-handling model influenced by that used by the Rust programming language See https://doc.rust-lang.org/book/ch09-00-error-handling.html. """ from typing import Generic, TypeVar, Union T = TypeVar("T") E = TypeVar("E", bound=Exception) class Ok(Generic[T]): def __init__(self, value: T) -> None: self._value = value def ok(self) -> T: return self._value class Err(Generic[E]): def __init__(self, e: E) -> None: self._e = e def err(self) -> E: return self._e Result = Union[Ok[T], Err[E]]
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/src/black/brackets.py
src/black/brackets.py
"""Builds on top of nodes.py to track brackets.""" from collections.abc import Iterable, Sequence from dataclasses import dataclass, field from typing import Final, Union from black.nodes import ( BRACKET, CLOSING_BRACKETS, COMPARATORS, LOGIC_OPERATORS, MATH_OPERATORS, OPENING_BRACKETS, UNPACKING_PARENTS, VARARGS_PARENTS, is_vararg, syms, ) from blib2to3.pgen2 import token from blib2to3.pytree import Leaf, Node # types LN = Union[Leaf, Node] Depth = int LeafID = int NodeType = int Priority = int COMPREHENSION_PRIORITY: Final = 20 COMMA_PRIORITY: Final = 18 TERNARY_PRIORITY: Final = 16 LOGIC_PRIORITY: Final = 14 STRING_PRIORITY: Final = 12 COMPARATOR_PRIORITY: Final = 10 MATH_PRIORITIES: Final = { token.VBAR: 9, token.CIRCUMFLEX: 8, token.AMPER: 7, token.LEFTSHIFT: 6, token.RIGHTSHIFT: 6, token.PLUS: 5, token.MINUS: 5, token.STAR: 4, token.SLASH: 4, token.DOUBLESLASH: 4, token.PERCENT: 4, token.AT: 4, token.TILDE: 3, token.DOUBLESTAR: 2, } DOT_PRIORITY: Final = 1 class BracketMatchError(Exception): """Raised when an opening bracket is unable to be matched to a closing bracket.""" @dataclass class BracketTracker: """Keeps track of brackets on a line.""" depth: int = 0 bracket_match: dict[tuple[Depth, NodeType], Leaf] = field(default_factory=dict) delimiters: dict[LeafID, Priority] = field(default_factory=dict) previous: Leaf | None = None _for_loop_depths: list[int] = field(default_factory=list) _lambda_argument_depths: list[int] = field(default_factory=list) invisible: list[Leaf] = field(default_factory=list) def mark(self, leaf: Leaf) -> None: """Mark `leaf` with bracket-related metadata. Keep track of delimiters. All leaves receive an int `bracket_depth` field that stores how deep within brackets a given leaf is. 0 means there are no enclosing brackets that started on this line. If a leaf is itself a closing bracket and there is a matching opening bracket earlier, it receives an `opening_bracket` field with which it forms a pair. This is a one-directional link to avoid reference cycles. Closing bracket without opening happens on lines continued from previous breaks, e.g. `) -> "ReturnType":` as part of a funcdef where we place the return type annotation on its own line of the previous closing RPAR. If a leaf is a delimiter (a token on which Black can split the line if needed) and it's on depth 0, its `id()` is stored in the tracker's `delimiters` field. """ if leaf.type == token.COMMENT: return if ( self.depth == 0 and leaf.type in CLOSING_BRACKETS and (self.depth, leaf.type) not in self.bracket_match ): return self.maybe_decrement_after_for_loop_variable(leaf) self.maybe_decrement_after_lambda_arguments(leaf) if leaf.type in CLOSING_BRACKETS: self.depth -= 1 try: opening_bracket = self.bracket_match.pop((self.depth, leaf.type)) except KeyError as e: raise BracketMatchError( "Unable to match a closing bracket to the following opening" f" bracket: {leaf}" ) from e leaf.opening_bracket = opening_bracket if not leaf.value: self.invisible.append(leaf) leaf.bracket_depth = self.depth if self.depth == 0: delim = is_split_before_delimiter(leaf, self.previous) if delim and self.previous is not None: self.delimiters[id(self.previous)] = delim else: delim = is_split_after_delimiter(leaf) if delim: self.delimiters[id(leaf)] = delim if leaf.type in OPENING_BRACKETS: self.bracket_match[self.depth, BRACKET[leaf.type]] = leaf self.depth += 1 if not leaf.value: self.invisible.append(leaf) self.previous = leaf self.maybe_increment_lambda_arguments(leaf) self.maybe_increment_for_loop_variable(leaf) def any_open_for_or_lambda(self) -> bool: """Return True if there is an open for or lambda expression on the line. See maybe_increment_for_loop_variable and maybe_increment_lambda_arguments for details.""" return bool(self._for_loop_depths or self._lambda_argument_depths) def any_open_brackets(self) -> bool: """Return True if there is an yet unmatched open bracket on the line.""" return bool(self.bracket_match) def max_delimiter_priority(self, exclude: Iterable[LeafID] = ()) -> Priority: """Return the highest priority of a delimiter found on the line. Values are consistent with what `is_split_*_delimiter()` return. Raises ValueError on no delimiters. """ return max(v for k, v in self.delimiters.items() if k not in exclude) def delimiter_count_with_priority(self, priority: Priority = 0) -> int: """Return the number of delimiters with the given `priority`. If no `priority` is passed, defaults to max priority on the line. """ if not self.delimiters: return 0 priority = priority or self.max_delimiter_priority() return sum(1 for p in self.delimiters.values() if p == priority) def maybe_increment_for_loop_variable(self, leaf: Leaf) -> bool: """In a for loop, or comprehension, the variables are often unpacks. To avoid splitting on the comma in this situation, increase the depth of tokens between `for` and `in`. """ if leaf.type == token.NAME and leaf.value == "for": self.depth += 1 self._for_loop_depths.append(self.depth) return True return False def maybe_decrement_after_for_loop_variable(self, leaf: Leaf) -> bool: """See `maybe_increment_for_loop_variable` above for explanation.""" if ( self._for_loop_depths and self._for_loop_depths[-1] == self.depth and leaf.type == token.NAME and leaf.value == "in" ): self.depth -= 1 self._for_loop_depths.pop() return True return False def maybe_increment_lambda_arguments(self, leaf: Leaf) -> bool: """In a lambda expression, there might be more than one argument. To avoid splitting on the comma in this situation, increase the depth of tokens between `lambda` and `:`. """ if leaf.type == token.NAME and leaf.value == "lambda": self.depth += 1 self._lambda_argument_depths.append(self.depth) return True return False def maybe_decrement_after_lambda_arguments(self, leaf: Leaf) -> bool: """See `maybe_increment_lambda_arguments` above for explanation.""" if ( self._lambda_argument_depths and self._lambda_argument_depths[-1] == self.depth and leaf.type == token.COLON ): self.depth -= 1 self._lambda_argument_depths.pop() return True return False def get_open_lsqb(self) -> Leaf | None: """Return the most recent opening square bracket (if any).""" return self.bracket_match.get((self.depth - 1, token.RSQB)) def is_split_after_delimiter(leaf: Leaf) -> Priority: """Return the priority of the `leaf` delimiter, given a line break after it. The delimiter priorities returned here are from those delimiters that would cause a line break after themselves. Higher numbers are higher priority. """ if leaf.type == token.COMMA: return COMMA_PRIORITY return 0 def is_split_before_delimiter(leaf: Leaf, previous: Leaf | None = None) -> Priority: """Return the priority of the `leaf` delimiter, given a line break before it. The delimiter priorities returned here are from those delimiters that would cause a line break before themselves. Higher numbers are higher priority. """ if is_vararg(leaf, within=VARARGS_PARENTS | UNPACKING_PARENTS): # * and ** might also be MATH_OPERATORS but in this case they are not. # Don't treat them as a delimiter. return 0 if ( leaf.type == token.DOT and leaf.parent and leaf.parent.type not in {syms.import_from, syms.dotted_name} and (previous is None or previous.type in CLOSING_BRACKETS) ): return DOT_PRIORITY if ( leaf.type in MATH_OPERATORS and leaf.parent and leaf.parent.type not in {syms.factor, syms.star_expr} ): return MATH_PRIORITIES[leaf.type] if leaf.type in COMPARATORS: return COMPARATOR_PRIORITY if ( leaf.type == token.STRING and previous is not None and previous.type == token.STRING ): return STRING_PRIORITY if leaf.type not in {token.NAME, token.ASYNC}: return 0 if ( leaf.value == "for" and leaf.parent and leaf.parent.type in {syms.comp_for, syms.old_comp_for} or leaf.type == token.ASYNC ): if ( not isinstance(leaf.prev_sibling, Leaf) or leaf.prev_sibling.value != "async" ): return COMPREHENSION_PRIORITY if ( leaf.value == "if" and leaf.parent and leaf.parent.type in {syms.comp_if, syms.old_comp_if} ): return COMPREHENSION_PRIORITY if leaf.value in {"if", "else"} and leaf.parent and leaf.parent.type == syms.test: return TERNARY_PRIORITY if leaf.value == "is": return COMPARATOR_PRIORITY if ( leaf.value == "in" and leaf.parent and leaf.parent.type in {syms.comp_op, syms.comparison} and not ( previous is not None and previous.type == token.NAME and previous.value == "not" ) ): return COMPARATOR_PRIORITY if ( leaf.value == "not" and leaf.parent and leaf.parent.type == syms.comp_op and not ( previous is not None and previous.type == token.NAME and previous.value == "is" ) ): return COMPARATOR_PRIORITY if leaf.value in LOGIC_OPERATORS and leaf.parent: return LOGIC_PRIORITY return 0 def max_delimiter_priority_in_atom(node: LN) -> Priority: """Return maximum delimiter priority inside `node`. This is specific to atoms with contents contained in a pair of parentheses. If `node` isn't an atom or there are no enclosing parentheses, returns 0. """ if node.type != syms.atom: return 0 first = node.children[0] last = node.children[-1] if not (first.type == token.LPAR and last.type == token.RPAR): return 0 bt = BracketTracker() for c in node.children[1:-1]: if isinstance(c, Leaf): bt.mark(c) else: for leaf in c.leaves(): bt.mark(leaf) try: return bt.max_delimiter_priority() except ValueError: return 0 def get_leaves_inside_matching_brackets(leaves: Sequence[Leaf]) -> set[LeafID]: """Return leaves that are inside matching brackets. The input `leaves` can have non-matching brackets at the head or tail parts. Matching brackets are included. """ try: # Start with the first opening bracket and ignore closing brackets before. start_index = next( i for i, l in enumerate(leaves) if l.type in OPENING_BRACKETS ) except StopIteration: return set() bracket_stack = [] ids = set() for i in range(start_index, len(leaves)): leaf = leaves[i] if leaf.type in OPENING_BRACKETS: bracket_stack.append((BRACKET[leaf.type], i)) if leaf.type in CLOSING_BRACKETS: if bracket_stack and leaf.type == bracket_stack[-1][0]: _, start = bracket_stack.pop() for j in range(start, i + 1): ids.add(id(leaves[j])) else: break return ids
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/src/black/nodes.py
src/black/nodes.py
""" blib2to3 Node/Leaf transformation-related utility functions. """ from collections.abc import Iterator from typing import Final, Generic, Literal, TypeGuard, TypeVar, Union from mypy_extensions import mypyc_attr from black.cache import CACHE_DIR from black.mode import Mode, Preview from black.strings import get_string_prefix, has_triple_quotes from blib2to3 import pygram from blib2to3.pgen2 import token from blib2to3.pytree import NL, Leaf, Node, type_repr pygram.initialize(CACHE_DIR) syms: Final = pygram.python_symbols # types T = TypeVar("T") LN = Union[Leaf, Node] LeafID = int NodeType = int WHITESPACE: Final = {token.DEDENT, token.INDENT, token.NEWLINE} STATEMENT: Final = { syms.if_stmt, syms.while_stmt, syms.for_stmt, syms.try_stmt, syms.except_clause, syms.with_stmt, syms.funcdef, syms.classdef, syms.match_stmt, syms.case_block, } STANDALONE_COMMENT: Final = 153 token.tok_name[STANDALONE_COMMENT] = "STANDALONE_COMMENT" LOGIC_OPERATORS: Final = {"and", "or"} COMPARATORS: Final = { token.LESS, token.GREATER, token.EQEQUAL, token.NOTEQUAL, token.LESSEQUAL, token.GREATEREQUAL, } MATH_OPERATORS: Final = { token.VBAR, token.CIRCUMFLEX, token.AMPER, token.LEFTSHIFT, token.RIGHTSHIFT, token.PLUS, token.MINUS, token.STAR, token.SLASH, token.DOUBLESLASH, token.PERCENT, token.AT, token.TILDE, token.DOUBLESTAR, } STARS: Final = {token.STAR, token.DOUBLESTAR} VARARGS_SPECIALS: Final = STARS | {token.SLASH} VARARGS_PARENTS: Final = { syms.arglist, syms.argument, # double star in arglist syms.trailer, # single argument to call syms.typedargslist, syms.varargslist, # lambdas } UNPACKING_PARENTS: Final = { syms.atom, # single element of a list or set literal syms.dictsetmaker, syms.listmaker, syms.testlist_gexp, syms.testlist_star_expr, syms.subject_expr, syms.pattern, } TEST_DESCENDANTS: Final = { syms.test, syms.lambdef, syms.or_test, syms.and_test, syms.not_test, syms.comparison, syms.star_expr, syms.expr, syms.xor_expr, syms.and_expr, syms.shift_expr, syms.arith_expr, syms.trailer, syms.term, syms.power, syms.namedexpr_test, } TYPED_NAMES: Final = {syms.tname, syms.tname_star} ASSIGNMENTS: Final = { "=", "+=", "-=", "*=", "@=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", "**=", "//=", ":", } IMPLICIT_TUPLE: Final = {syms.testlist, syms.testlist_star_expr, syms.exprlist} BRACKET: Final = { token.LPAR: token.RPAR, token.LSQB: token.RSQB, token.LBRACE: token.RBRACE, } OPENING_BRACKETS: Final = set(BRACKET.keys()) CLOSING_BRACKETS: Final = set(BRACKET.values()) BRACKETS: Final = OPENING_BRACKETS | CLOSING_BRACKETS ALWAYS_NO_SPACE: Final = CLOSING_BRACKETS | { token.COMMA, STANDALONE_COMMENT, token.FSTRING_MIDDLE, token.FSTRING_END, token.TSTRING_MIDDLE, token.TSTRING_END, token.BANG, } RARROW = 55 @mypyc_attr(allow_interpreted_subclasses=True) class Visitor(Generic[T]): """Basic lib2to3 visitor that yields things of type `T` on `visit()`.""" def visit(self, node: LN) -> Iterator[T]: """Main method to visit `node` and its children. It tries to find a `visit_*()` method for the given `node.type`, like `visit_simple_stmt` for Node objects or `visit_INDENT` for Leaf objects. If no dedicated `visit_*()` method is found, chooses `visit_default()` instead. Then yields objects of type `T` from the selected visitor. """ if node.type < 256: name = token.tok_name[node.type] else: name = str(type_repr(node.type)) # We explicitly branch on whether a visitor exists (instead of # using self.visit_default as the default arg to getattr) in order # to save needing to create a bound method object and so mypyc can # generate a native call to visit_default. visitf = getattr(self, f"visit_{name}", None) if visitf: yield from visitf(node) else: yield from self.visit_default(node) def visit_default(self, node: LN) -> Iterator[T]: """Default `visit_*()` implementation. Recurses to children of `node`.""" if isinstance(node, Node): for child in node.children: yield from self.visit(child) def whitespace(leaf: Leaf, *, complex_subscript: bool, mode: Mode) -> str: """Return whitespace prefix if needed for the given `leaf`. `complex_subscript` signals whether the given leaf is part of a subscription which has non-trivial arguments, like arithmetic expressions or function calls. """ NO: Final[str] = "" SPACE: Final[str] = " " DOUBLESPACE: Final[str] = " " t = leaf.type p = leaf.parent v = leaf.value if t in ALWAYS_NO_SPACE: return NO if t == token.COMMENT: return DOUBLESPACE assert p is not None, f"INTERNAL ERROR: hand-made leaf without parent: {leaf!r}" if t == token.COLON and p.type not in { syms.subscript, syms.subscriptlist, syms.sliceop, }: return NO if t == token.LBRACE and p.type in ( syms.fstring_replacement_field, syms.tstring_replacement_field, ): return NO prev = leaf.prev_sibling if not prev: prevp = preceding_leaf(p) if not prevp or prevp.type in OPENING_BRACKETS: return NO if t == token.COLON: if prevp.type == token.COLON: return NO elif prevp.type != token.COMMA and not complex_subscript: return NO return SPACE if prevp.type == token.EQUAL: if prevp.parent: if prevp.parent.type in { syms.arglist, syms.argument, syms.parameters, syms.varargslist, }: return NO elif prevp.parent.type == syms.typedargslist: # A bit hacky: if the equal sign has whitespace, it means we # previously found it's a typed argument. So, we're using # that, too. return prevp.prefix elif ( prevp.type == token.STAR and parent_type(prevp) == syms.star_expr and parent_type(prevp.parent) in (syms.subscriptlist, syms.tname_star) ): # No space between typevar tuples or unpacking them. return NO elif prevp.type in VARARGS_SPECIALS: if is_vararg(prevp, within=VARARGS_PARENTS | UNPACKING_PARENTS): return NO elif prevp.type == token.COLON: if prevp.parent and prevp.parent.type in {syms.subscript, syms.sliceop}: return SPACE if complex_subscript else NO elif ( prevp.parent and prevp.parent.type == syms.factor and prevp.type in MATH_OPERATORS ): return NO elif prevp.type == token.AT and p.parent and p.parent.type == syms.decorator: # no space in decorators return NO elif prev.type in OPENING_BRACKETS: return NO elif prev.type == token.BANG: return NO if p.type in {syms.parameters, syms.arglist}: # untyped function signatures or calls if not prev or prev.type != token.COMMA: return NO elif p.type == syms.varargslist: # lambdas if prev and prev.type != token.COMMA: return NO elif p.type == syms.typedargslist: # typed function signatures if not prev: return NO if t == token.EQUAL: if prev.type not in TYPED_NAMES: return NO elif prev.type == token.EQUAL: # A bit hacky: if the equal sign has whitespace, it means we # previously found it's a typed argument. So, we're using that, too. return prev.prefix elif prev.type != token.COMMA: return NO elif p.type in TYPED_NAMES: # type names if not prev: prevp = preceding_leaf(p) if not prevp or prevp.type != token.COMMA: return NO elif p.type == syms.trailer: # attributes and calls if t == token.LPAR or t == token.RPAR: return NO if not prev: if t == token.DOT or t == token.LSQB: return NO elif prev.type != token.COMMA: return NO elif p.type == syms.argument: # single argument if t == token.EQUAL: return NO if not prev: prevp = preceding_leaf(p) if not prevp or prevp.type == token.LPAR: return NO elif prev.type in {token.EQUAL} | VARARGS_SPECIALS: return NO elif p.type == syms.decorator: # decorators return NO elif p.type == syms.dotted_name: if prev: return NO prevp = preceding_leaf(p) if not prevp or prevp.type == token.AT or prevp.type == token.DOT: return NO elif p.type == syms.classdef: if t == token.LPAR: return NO if prev and prev.type == token.LPAR: return NO elif p.type in {syms.subscript, syms.sliceop}: # indexing if not prev: assert p.parent is not None, "subscripts are always parented" if p.parent.type == syms.subscriptlist: return SPACE return NO elif t == token.COLONEQUAL or prev.type == token.COLONEQUAL: return SPACE elif not complex_subscript: return NO elif p.type == syms.atom: if prev and t == token.DOT: # dots, but not the first one. return NO elif p.type == syms.dictsetmaker: # dict unpacking if prev and prev.type == token.DOUBLESTAR: return NO elif p.type in {syms.factor, syms.star_expr}: # unary ops if not prev: prevp = preceding_leaf(p) if not prevp or prevp.type in OPENING_BRACKETS: return NO prevp_parent = prevp.parent assert prevp_parent is not None if prevp.type == token.COLON and prevp_parent.type in { syms.subscript, syms.sliceop, }: return NO elif prevp.type == token.EQUAL and prevp_parent.type == syms.argument: return NO elif t in {token.NAME, token.NUMBER, token.STRING}: return NO elif p.type == syms.import_from: if t == token.DOT: if prev and prev.type == token.DOT: return NO elif t == token.NAME: if v == "import": return SPACE if prev and prev.type == token.DOT: return NO elif p.type == syms.sliceop: return NO elif p.type == syms.except_clause: if t == token.STAR: return NO return SPACE def make_simple_prefix(nl_count: int, form_feed: bool, empty_line: str = "\n") -> str: """Generate a normalized prefix string.""" if form_feed: return (empty_line * (nl_count - 1)) + "\f" + empty_line return empty_line * nl_count def preceding_leaf(node: LN | None) -> Leaf | None: """Return the first leaf that precedes `node`, if any.""" while node: res = node.prev_sibling if res: if isinstance(res, Leaf): return res try: return list(res.leaves())[-1] except IndexError: return None node = node.parent return None def prev_siblings_are(node: LN | None, tokens: list[NodeType | None]) -> bool: """Return if the `node` and its previous siblings match types against the provided list of tokens; the provided `node`has its type matched against the last element in the list. `None` can be used as the first element to declare that the start of the list is anchored at the start of its parent's children.""" if not tokens: return True if tokens[-1] is None: return node is None if not node: return False if node.type != tokens[-1]: return False return prev_siblings_are(node.prev_sibling, tokens[:-1]) def parent_type(node: LN | None) -> NodeType | None: """ Returns: @node.parent.type, if @node is not None and has a parent. OR None, otherwise. """ if node is None or node.parent is None: return None return node.parent.type def child_towards(ancestor: Node, descendant: LN) -> LN | None: """Return the child of `ancestor` that contains `descendant`.""" node: LN | None = descendant while node and node.parent != ancestor: node = node.parent return node def replace_child(old_child: LN, new_child: LN) -> None: """ Side Effects: * If @old_child.parent is set, replace @old_child with @new_child in @old_child's underlying Node structure. OR * Otherwise, this function does nothing. """ parent = old_child.parent if not parent: return child_idx = old_child.remove() if child_idx is not None: parent.insert_child(child_idx, new_child) def container_of(leaf: Leaf) -> LN: """Return `leaf` or one of its ancestors that is the topmost container of it. By "container" we mean a node where `leaf` is the very first child. """ same_prefix = leaf.prefix container: LN = leaf while container: parent = container.parent if parent is None: break if parent.children[0].prefix != same_prefix: break if parent.type == syms.file_input: break if parent.prev_sibling is not None and parent.prev_sibling.type in BRACKETS: break container = parent return container def first_leaf_of(node: LN) -> Leaf | None: """Returns the first leaf of the node tree.""" if isinstance(node, Leaf): return node if node.children: return first_leaf_of(node.children[0]) else: return None def is_arith_like(node: LN) -> bool: """Whether node is an arithmetic or a binary arithmetic expression""" return node.type in { syms.arith_expr, syms.shift_expr, syms.xor_expr, syms.and_expr, } def is_docstring(node: NL) -> bool: if isinstance(node, Leaf): if node.type != token.STRING: return False prefix = get_string_prefix(node.value) if set(prefix).intersection("bBfF"): return False if ( node.parent and node.parent.type == syms.simple_stmt and not node.parent.prev_sibling and node.parent.parent and node.parent.parent.type == syms.file_input ): return True if prev_siblings_are( node.parent, [None, token.NEWLINE, token.INDENT, syms.simple_stmt] ): return True # Multiline docstring on the same line as the `def`. if prev_siblings_are(node.parent, [syms.parameters, token.COLON, syms.simple_stmt]): # `syms.parameters` is only used in funcdefs and async_funcdefs in the Python # grammar. We're safe to return True without further checks. return True return False def is_empty_tuple(node: LN) -> bool: """Return True if `node` holds an empty tuple.""" return ( node.type == syms.atom and len(node.children) == 2 and node.children[0].type == token.LPAR and node.children[1].type == token.RPAR ) def is_one_tuple(node: LN) -> bool: """Return True if `node` holds a tuple with one element, with or without parens.""" if node.type == syms.atom: gexp = unwrap_singleton_parenthesis(node) if gexp is None or gexp.type != syms.testlist_gexp: return False return len(gexp.children) == 2 and gexp.children[1].type == token.COMMA return ( node.type in IMPLICIT_TUPLE and len(node.children) == 2 and node.children[1].type == token.COMMA ) def is_tuple(node: LN) -> bool: """Return True if `node` holds a tuple.""" if node.type != syms.atom: return False gexp = unwrap_singleton_parenthesis(node) if gexp is None or gexp.type != syms.testlist_gexp: return False return True def is_tuple_containing_walrus(node: LN) -> bool: """Return True if `node` holds a tuple that contains a walrus operator.""" if node.type != syms.atom: return False gexp = unwrap_singleton_parenthesis(node) if gexp is None or gexp.type != syms.testlist_gexp: return False return any(child.type == syms.namedexpr_test for child in gexp.children) def is_tuple_containing_star(node: LN) -> bool: """Return True if `node` holds a tuple that contains a star operator.""" if node.type != syms.atom: return False gexp = unwrap_singleton_parenthesis(node) if gexp is None or gexp.type != syms.testlist_gexp: return False return any(child.type == syms.star_expr for child in gexp.children) def is_generator(node: LN) -> bool: """Return True if `node` holds a generator.""" if node.type != syms.atom: return False gexp = unwrap_singleton_parenthesis(node) if gexp is None or gexp.type != syms.testlist_gexp: return False return any(child.type == syms.old_comp_for for child in gexp.children) def is_one_sequence_between( opening: Leaf, closing: Leaf, leaves: list[Leaf], brackets: tuple[int, int] = (token.LPAR, token.RPAR), ) -> bool: """Return True if content between `opening` and `closing` is a one-sequence.""" if (opening.type, closing.type) != brackets: return False depth = closing.bracket_depth + 1 for _opening_index, leaf in enumerate(leaves): if leaf is opening: break else: raise LookupError("Opening paren not found in `leaves`") commas = 0 _opening_index += 1 for leaf in leaves[_opening_index:]: if leaf is closing: break bracket_depth = leaf.bracket_depth if bracket_depth == depth and leaf.type == token.COMMA: commas += 1 if leaf.parent and leaf.parent.type in { syms.arglist, syms.typedargslist, }: commas += 1 break return commas < 2 def is_walrus_assignment(node: LN) -> bool: """Return True iff `node` is of the shape ( test := test )""" inner = unwrap_singleton_parenthesis(node) return inner is not None and inner.type == syms.namedexpr_test def is_simple_decorator_trailer(node: LN, last: bool = False) -> bool: """Return True iff `node` is a trailer valid in a simple decorator""" return node.type == syms.trailer and ( ( len(node.children) == 2 and node.children[0].type == token.DOT and node.children[1].type == token.NAME ) # last trailer can be an argument-less parentheses pair or ( last and len(node.children) == 2 and node.children[0].type == token.LPAR and node.children[1].type == token.RPAR ) # last trailer can be arguments or ( last and len(node.children) == 3 and node.children[0].type == token.LPAR # and node.children[1].type == syms.argument and node.children[2].type == token.RPAR ) ) def is_simple_decorator_expression(node: LN) -> bool: """Return True iff `node` could be a 'dotted name' decorator This function takes the node of the 'namedexpr_test' of the new decorator grammar and test if it would be valid under the old decorator grammar. The old grammar was: decorator: @ dotted_name [arguments] NEWLINE The new grammar is : decorator: @ namedexpr_test NEWLINE """ if node.type == token.NAME: return True if node.type == syms.power: if node.children: return ( node.children[0].type == token.NAME and all(map(is_simple_decorator_trailer, node.children[1:-1])) and ( len(node.children) < 2 or is_simple_decorator_trailer(node.children[-1], last=True) ) ) return False def is_yield(node: LN) -> bool: """Return True if `node` holds a `yield` or `yield from` expression.""" if node.type == syms.yield_expr: return True if is_name_token(node) and node.value == "yield": return True if node.type != syms.atom: return False if len(node.children) != 3: return False lpar, expr, rpar = node.children if lpar.type == token.LPAR and rpar.type == token.RPAR: return is_yield(expr) return False def is_vararg(leaf: Leaf, within: set[NodeType]) -> bool: """Return True if `leaf` is a star or double star in a vararg or kwarg. If `within` includes VARARGS_PARENTS, this applies to function signatures. If `within` includes UNPACKING_PARENTS, it applies to right hand-side extended iterable unpacking (PEP 3132) and additional unpacking generalizations (PEP 448). """ if leaf.type not in VARARGS_SPECIALS or not leaf.parent: return False p = leaf.parent if p.type == syms.star_expr: # Star expressions are also used as assignment targets in extended # iterable unpacking (PEP 3132). See what its parent is instead. if not p.parent: return False p = p.parent return p.type in within def is_fstring(node: Node) -> bool: """Return True if the node is an f-string""" return node.type == syms.fstring def fstring_tstring_to_string(node: Node) -> Leaf: """Converts an fstring or tstring node back to a string node.""" string_without_prefix = str(node)[len(node.prefix) :] string_leaf = Leaf(token.STRING, string_without_prefix, prefix=node.prefix) string_leaf.lineno = node.get_lineno() or 0 return string_leaf def is_multiline_string(node: LN) -> bool: """Return True if `leaf` is a multiline string that actually spans many lines.""" if isinstance(node, Node) and is_fstring(node): leaf = fstring_tstring_to_string(node) elif isinstance(node, Leaf): leaf = node else: return False return has_triple_quotes(leaf.value) and "\n" in leaf.value def is_parent_function_or_class(node: Node) -> bool: assert node.type in {syms.suite, syms.simple_stmt} assert node.parent is not None # Note this works for suites / simple_stmts in async def as well return node.parent.type in {syms.funcdef, syms.classdef} def is_function_or_class(node: Node) -> bool: return node.type in {syms.funcdef, syms.classdef, syms.async_funcdef} def is_stub_suite(node: Node) -> bool: """Return True if `node` is a suite with a stub body.""" if node.parent is not None and not is_parent_function_or_class(node): return False # If there is a comment, we want to keep it. if node.prefix.strip(): return False if ( len(node.children) != 4 or node.children[0].type != token.NEWLINE or node.children[1].type != token.INDENT or node.children[3].type != token.DEDENT ): return False if node.children[3].prefix.strip(): return False return is_stub_body(node.children[2]) def is_stub_body(node: LN) -> bool: """Return True if `node` is a simple statement containing an ellipsis.""" if not isinstance(node, Node) or node.type != syms.simple_stmt: return False if len(node.children) != 2: return False child = node.children[0] return ( not child.prefix.strip() and child.type == syms.atom and len(child.children) == 3 and all(leaf == Leaf(token.DOT, ".") for leaf in child.children) ) def is_atom_with_invisible_parens(node: LN) -> bool: """Given a `LN`, determines whether it's an atom `node` with invisible parens. Useful in dedupe-ing and normalizing parens. """ if isinstance(node, Leaf) or node.type != syms.atom: return False first, last = node.children[0], node.children[-1] return ( isinstance(first, Leaf) and first.type == token.LPAR and first.value == "" and isinstance(last, Leaf) and last.type == token.RPAR and last.value == "" ) def is_empty_par(leaf: Leaf) -> bool: return is_empty_lpar(leaf) or is_empty_rpar(leaf) def is_empty_lpar(leaf: Leaf) -> bool: return leaf.type == token.LPAR and leaf.value == "" def is_empty_rpar(leaf: Leaf) -> bool: return leaf.type == token.RPAR and leaf.value == "" def is_import(leaf: Leaf) -> bool: """Return True if the given leaf starts an import statement.""" p = leaf.parent t = leaf.type v = leaf.value return bool( t == token.NAME and ( (v == "import" and p and p.type == syms.import_name) or (v == "from" and p and p.type == syms.import_from) ) ) def is_with_or_async_with_stmt(leaf: Leaf) -> bool: """Return True if the given leaf starts a with or async with statement.""" return bool( leaf.type == token.NAME and leaf.value == "with" and leaf.parent and leaf.parent.type == syms.with_stmt ) or bool( leaf.type == token.ASYNC and leaf.next_sibling and leaf.next_sibling.type == syms.with_stmt ) def is_async_stmt_or_funcdef(leaf: Leaf) -> bool: """Return True if the given leaf starts an async def/for/with statement. Note that `async def` can be either an `async_stmt` or `async_funcdef`, the latter is used when it has decorators. """ return bool( leaf.type == token.ASYNC and leaf.parent and leaf.parent.type in {syms.async_stmt, syms.async_funcdef} ) def is_type_comment(leaf: Leaf, mode: Mode) -> bool: """Return True if the given leaf is a type comment. This function should only be used for general type comments (excluding ignore annotations, which should use `is_type_ignore_comment`). Note that general type comments are no longer used in modern version of Python, this function may be deprecated in the future.""" t = leaf.type v = leaf.value return t in {token.COMMENT, STANDALONE_COMMENT} and is_type_comment_string(v, mode) def is_type_comment_string(value: str, mode: Mode) -> bool: if Preview.standardize_type_comments in mode: is_valid = value.startswith("#") and value[1:].lstrip().startswith("type:") else: is_valid = value.startswith("# type:") return is_valid def is_type_ignore_comment(leaf: Leaf, mode: Mode) -> bool: """Return True if the given leaf is a type comment with ignore annotation.""" t = leaf.type v = leaf.value return t in {token.COMMENT, STANDALONE_COMMENT} and is_type_ignore_comment_string( v, mode ) def is_type_ignore_comment_string(value: str, mode: Mode) -> bool: """Return True if the given string match with type comment with ignore annotation.""" if Preview.standardize_type_comments in mode: is_valid = is_type_comment_string(value, mode) and value.split(":", 1)[ 1 ].lstrip().startswith("ignore") else: is_valid = value.startswith("# type: ignore") return is_valid def wrap_in_parentheses(parent: Node, child: LN, *, visible: bool = True) -> None: """Wrap `child` in parentheses. This replaces `child` with an atom holding the parentheses and the old child. That requires moving the prefix. If `visible` is False, the leaves will be valueless (and thus invisible). """ lpar = Leaf(token.LPAR, "(" if visible else "") rpar = Leaf(token.RPAR, ")" if visible else "") prefix = child.prefix child.prefix = "" index = child.remove() or 0 new_child = Node(syms.atom, [lpar, child, rpar]) new_child.prefix = prefix parent.insert_child(index, new_child) def unwrap_singleton_parenthesis(node: LN) -> LN | None: """Returns `wrapped` if `node` is of the shape ( wrapped ). Parenthesis can be optional. Returns None otherwise""" if len(node.children) != 3: return None lpar, wrapped, rpar = node.children if not (lpar.type == token.LPAR and rpar.type == token.RPAR): return None return wrapped def ensure_visible(leaf: Leaf) -> None: """Make sure parentheses are visible. They could be invisible as part of some statements (see :func:`normalize_invisible_parens` and :func:`visit_import_from`). """ if leaf.type == token.LPAR: leaf.value = "(" elif leaf.type == token.RPAR: leaf.value = ")" def is_name_token(nl: NL) -> TypeGuard[Leaf]: return nl.type == token.NAME def is_lpar_token(nl: NL) -> TypeGuard[Leaf]: return nl.type == token.LPAR def is_rpar_token(nl: NL) -> TypeGuard[Leaf]: return nl.type == token.RPAR def is_number_token(nl: NL) -> TypeGuard[Leaf]: return nl.type == token.NUMBER def get_annotation_type(leaf: Leaf) -> Literal["return", "param", None]: """Returns the type of annotation this leaf is part of, if any.""" ancestor = leaf.parent while ancestor is not None: if ancestor.prev_sibling and ancestor.prev_sibling.type == token.RARROW: return "return" if ancestor.parent and ancestor.parent.type == syms.tname: return "param" ancestor = ancestor.parent return None def is_part_of_annotation(leaf: Leaf) -> bool: """Returns whether this leaf is part of a type annotation.""" assert leaf.parent is not None return get_annotation_type(leaf) is not None def first_leaf(node: LN) -> Leaf | None: """Returns the first leaf of the ancestor node.""" if isinstance(node, Leaf): return node elif not node.children: return None else: return first_leaf(node.children[0]) def last_leaf(node: LN) -> Leaf | None: """Returns the last leaf of the ancestor node.""" if isinstance(node, Leaf): return node elif not node.children: return None else: return last_leaf(node.children[-1]) def furthest_ancestor_with_last_leaf(leaf: Leaf) -> LN: """Returns the furthest ancestor that has this leaf node as the last leaf.""" node: LN = leaf while node.parent and node.parent.children and node is node.parent.children[-1]: node = node.parent return node def has_sibling_with_type(node: LN, type: int) -> bool: # Check previous siblings sibling = node.prev_sibling while sibling is not None: if sibling.type == type: return True sibling = sibling.prev_sibling # Check next siblings sibling = node.next_sibling while sibling is not None: if sibling.type == type: return True sibling = sibling.next_sibling return False
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/src/black/__main__.py
src/black/__main__.py
from black import patched_main patched_main()
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/src/black/const.py
src/black/const.py
DEFAULT_LINE_LENGTH = 88 DEFAULT_EXCLUDES = r"/(\.direnv|\.eggs|\.git|\.hg|\.ipynb_checkpoints|\.mypy_cache|\.nox|\.pytest_cache|\.ruff_cache|\.tox|\.svn|\.venv|\.vscode|__pypackages__|_build|buck-out|build|dist|venv)/" # noqa: B950 DEFAULT_INCLUDES = r"(\.pyi?|\.ipynb)$" STDIN_PLACEHOLDER = "__BLACK_STDIN_FILENAME__"
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/src/black/files.py
src/black/files.py
import io import os import sys from collections.abc import Iterable, Iterator, Sequence from functools import lru_cache from pathlib import Path from re import Pattern from typing import TYPE_CHECKING, Any, Union from mypy_extensions import mypyc_attr from packaging.specifiers import InvalidSpecifier, Specifier, SpecifierSet from packaging.version import InvalidVersion, Version from pathspec import PathSpec from pathspec.patterns.gitwildmatch import GitWildMatchPatternError if sys.version_info >= (3, 11): try: import tomllib except ImportError: # Help users on older alphas if not TYPE_CHECKING: import tomli as tomllib else: import tomli as tomllib from black.handle_ipynb_magics import jupyter_dependencies_are_installed from black.mode import TargetVersion from black.output import err from black.report import Report if TYPE_CHECKING: import colorama @lru_cache def _load_toml(path: Path | str) -> dict[str, Any]: with open(path, "rb") as f: return tomllib.load(f) @lru_cache def _cached_resolve(path: Path) -> Path: return path.resolve() @lru_cache def find_project_root( srcs: Sequence[str], stdin_filename: str | None = None ) -> tuple[Path, str]: """Return a directory containing .git, .hg, or pyproject.toml. pyproject.toml files are only considered if they contain a [tool.black] section and are ignored otherwise. That directory will be a common parent of all files and directories passed in `srcs`. If no directory in the tree contains a marker that would specify it's the project root, the root of the file system is returned. Returns a two-tuple with the first element as the project root path and the second element as a string describing the method by which the project root was discovered. """ if stdin_filename is not None: srcs = tuple(stdin_filename if s == "-" else s for s in srcs) if not srcs: srcs = [str(_cached_resolve(Path.cwd()))] path_srcs = [_cached_resolve(Path(Path.cwd(), src)) for src in srcs] # A list of lists of parents for each 'src'. 'src' is included as a # "parent" of itself if it is a directory src_parents = [ list(path.parents) + ([path] if path.is_dir() else []) for path in path_srcs ] common_base = max( set.intersection(*(set(parents) for parents in src_parents)), key=lambda path: path.parts, ) for directory in (common_base, *common_base.parents): if (directory / ".git").exists(): return directory, ".git directory" if (directory / ".hg").is_dir(): return directory, ".hg directory" if (directory / "pyproject.toml").is_file(): pyproject_toml = _load_toml(directory / "pyproject.toml") if "black" in pyproject_toml.get("tool", {}): return directory, "pyproject.toml" return directory, "file system root" def find_pyproject_toml( path_search_start: tuple[str, ...], stdin_filename: str | None = None ) -> str | None: """Find the absolute filepath to a pyproject.toml if it exists""" path_project_root, _ = find_project_root(path_search_start, stdin_filename) path_pyproject_toml = path_project_root / "pyproject.toml" if path_pyproject_toml.is_file(): return str(path_pyproject_toml) try: path_user_pyproject_toml = find_user_pyproject_toml() return ( str(path_user_pyproject_toml) if path_user_pyproject_toml.is_file() else None ) except (PermissionError, RuntimeError) as e: # We do not have access to the user-level config directory, so ignore it. err(f"Ignoring user configuration directory due to {e!r}") return None @mypyc_attr(patchable=True) def parse_pyproject_toml(path_config: str) -> dict[str, Any]: """Parse a pyproject toml file, pulling out relevant parts for Black. If parsing fails, will raise a tomllib.TOMLDecodeError. """ pyproject_toml = _load_toml(path_config) config: dict[str, Any] = pyproject_toml.get("tool", {}).get("black", {}) config = {k.replace("--", "").replace("-", "_"): v for k, v in config.items()} if "target_version" not in config: inferred_target_version = infer_target_version(pyproject_toml) if inferred_target_version is not None: config["target_version"] = [v.name.lower() for v in inferred_target_version] return config def infer_target_version( pyproject_toml: dict[str, Any], ) -> list[TargetVersion] | None: """Infer Black's target version from the project metadata in pyproject.toml. Supports the PyPA standard format (PEP 621): https://packaging.python.org/en/latest/specifications/declaring-project-metadata/#requires-python If the target version cannot be inferred, returns None. """ project_metadata = pyproject_toml.get("project", {}) requires_python = project_metadata.get("requires-python", None) if requires_python is not None: try: return parse_req_python_version(requires_python) except InvalidVersion: pass try: return parse_req_python_specifier(requires_python) except (InvalidSpecifier, InvalidVersion): pass return None def parse_req_python_version(requires_python: str) -> list[TargetVersion] | None: """Parse a version string (i.e. ``"3.7"``) to a list of TargetVersion. If parsing fails, will raise a packaging.version.InvalidVersion error. If the parsed version cannot be mapped to a valid TargetVersion, returns None. """ version = Version(requires_python) if version.release[0] != 3: return None try: return [TargetVersion(version.release[1])] except (IndexError, ValueError): return None def parse_req_python_specifier(requires_python: str) -> list[TargetVersion] | None: """Parse a specifier string (i.e. ``">=3.7,<3.10"``) to a list of TargetVersion. If parsing fails, will raise a packaging.specifiers.InvalidSpecifier error. If the parsed specifier cannot be mapped to a valid TargetVersion, returns None. """ specifier_set = strip_specifier_set(SpecifierSet(requires_python)) if not specifier_set: return None target_version_map = {f"3.{v.value}": v for v in TargetVersion} compatible_versions: list[str] = list(specifier_set.filter(target_version_map)) if compatible_versions: return [target_version_map[v] for v in compatible_versions] return None def strip_specifier_set(specifier_set: SpecifierSet) -> SpecifierSet: """Strip minor versions for some specifiers in the specifier set. For background on version specifiers, see PEP 440: https://peps.python.org/pep-0440/#version-specifiers """ specifiers = [] for s in specifier_set: if "*" in str(s): specifiers.append(s) elif s.operator in ["~=", "==", ">=", "==="]: version = Version(s.version) stripped = Specifier(f"{s.operator}{version.major}.{version.minor}") specifiers.append(stripped) elif s.operator == ">": version = Version(s.version) if len(version.release) > 2: s = Specifier(f">={version.major}.{version.minor}") specifiers.append(s) else: specifiers.append(s) return SpecifierSet(",".join(str(s) for s in specifiers)) @lru_cache def find_user_pyproject_toml() -> Path: r"""Return the path to the top-level user configuration for black. This looks for ~\.black on Windows and ~/.config/black on Linux and other Unix systems. May raise: - RuntimeError: if the current user has no homedir - PermissionError: if the current process cannot access the user's homedir """ if sys.platform == "win32": # Windows user_config_path = Path.home() / ".black" else: config_root = os.environ.get("XDG_CONFIG_HOME", "~/.config") user_config_path = Path(config_root).expanduser() / "black" return _cached_resolve(user_config_path) @lru_cache def get_gitignore(root: Path) -> PathSpec: """Return a PathSpec matching gitignore content if present.""" gitignore = root / ".gitignore" lines: list[str] = [] if gitignore.is_file(): with gitignore.open(encoding="utf-8") as gf: lines = gf.readlines() try: return PathSpec.from_lines("gitwildmatch", lines) except GitWildMatchPatternError as e: err(f"Could not parse {gitignore}: {e}") raise def resolves_outside_root_or_cannot_stat( path: Path, root: Path, report: Report | None = None, ) -> bool: """ Returns whether the path is a symbolic link that points outside the root directory. Also returns True if we failed to resolve the path. """ try: resolved_path = _cached_resolve(path) except OSError as e: if report: report.path_ignored(path, f"cannot be read because {e}") return True try: resolved_path.relative_to(root) except ValueError: if report: report.path_ignored(path, f"is a symbolic link that points outside {root}") return True return False def best_effort_relative_path(path: Path, root: Path) -> Path: # Precondition: resolves_outside_root_or_cannot_stat(path, root) is False try: return path.absolute().relative_to(root) except ValueError: pass root_parent = next((p for p in path.parents if _cached_resolve(p) == root), None) if root_parent is not None: return path.relative_to(root_parent) # something adversarial, fallback to path guaranteed by precondition return _cached_resolve(path).relative_to(root) def _path_is_ignored( root_relative_path: str, root: Path, gitignore_dict: dict[Path, PathSpec], ) -> bool: path = root / root_relative_path # Note that this logic is sensitive to the ordering of gitignore_dict. Callers must # ensure that gitignore_dict is ordered from least specific to most specific. for gitignore_path, pattern in gitignore_dict.items(): try: relative_path = path.relative_to(gitignore_path).as_posix() if path.is_dir(): relative_path = relative_path + "/" except ValueError: break if pattern.match_file(relative_path): return True return False def path_is_excluded( normalized_path: str, pattern: Pattern[str] | None, ) -> bool: match = pattern.search(normalized_path) if pattern else None return bool(match and match.group(0)) def gen_python_files( paths: Iterable[Path], root: Path, include: Pattern[str], exclude: Pattern[str], extend_exclude: Pattern[str] | None, force_exclude: Pattern[str] | None, report: Report, gitignore_dict: dict[Path, PathSpec] | None, *, verbose: bool, quiet: bool, ) -> Iterator[Path]: """Generate all files under `path` whose paths are not excluded by the `exclude_regex`, `extend_exclude`, or `force_exclude` regexes, but are included by the `include` regex. Symbolic links pointing outside of the `root` directory are ignored. `report` is where output about exclusions goes. """ assert root.is_absolute(), f"INTERNAL ERROR: `root` must be absolute but is {root}" for child in paths: assert child.is_absolute() root_relative_path = child.relative_to(root).as_posix() # First ignore files matching .gitignore, if passed if gitignore_dict and _path_is_ignored( root_relative_path, root, gitignore_dict ): report.path_ignored(child, "matches a .gitignore file content") continue # Then ignore with `--exclude` `--extend-exclude` and `--force-exclude` options. root_relative_path = "/" + root_relative_path if child.is_dir(): root_relative_path += "/" if path_is_excluded(root_relative_path, exclude): report.path_ignored(child, "matches the --exclude regular expression") continue if path_is_excluded(root_relative_path, extend_exclude): report.path_ignored( child, "matches the --extend-exclude regular expression" ) continue if path_is_excluded(root_relative_path, force_exclude): report.path_ignored(child, "matches the --force-exclude regular expression") continue if resolves_outside_root_or_cannot_stat(child, root, report): continue if child.is_dir(): # If gitignore is None, gitignore usage is disabled, while a Falsey # gitignore is when the directory doesn't have a .gitignore file. if gitignore_dict is not None: new_gitignore_dict = { **gitignore_dict, root / child: get_gitignore(child), } else: new_gitignore_dict = None yield from gen_python_files( child.iterdir(), root, include, exclude, extend_exclude, force_exclude, report, new_gitignore_dict, verbose=verbose, quiet=quiet, ) elif child.is_file(): if child.suffix == ".ipynb" and not jupyter_dependencies_are_installed( warn=verbose or not quiet ): continue include_match = include.search(root_relative_path) if include else True if include_match: yield child def wrap_stream_for_windows( f: io.TextIOWrapper, ) -> Union[io.TextIOWrapper, "colorama.AnsiToWin32"]: """ Wrap stream with colorama's wrap_stream so colors are shown on Windows. If `colorama` is unavailable, the original stream is returned unmodified. Otherwise, the `wrap_stream()` function determines whether the stream needs to be wrapped for a Windows environment and will accordingly either return an `AnsiToWin32` wrapper or the original stream. """ try: from colorama.initialise import wrap_stream except ImportError: return f else: # Set `strip=False` to avoid needing to modify test_express_diff_with_color. return wrap_stream(f, convert=None, strip=False, autoreset=False, wrap=True)
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/src/black/parsing.py
src/black/parsing.py
""" Parse Python code and perform AST validation. """ import ast import sys import warnings from collections.abc import Collection, Iterator from black.mode import VERSION_TO_FEATURES, Feature, TargetVersion, supports_feature from black.nodes import syms from blib2to3 import pygram from blib2to3.pgen2 import driver from blib2to3.pgen2.grammar import Grammar from blib2to3.pgen2.parse import ParseError from blib2to3.pgen2.tokenize import TokenError from blib2to3.pytree import Leaf, Node class InvalidInput(ValueError): """Raised when input source code fails all parse attempts.""" def get_grammars(target_versions: set[TargetVersion]) -> list[Grammar]: if not target_versions: # No target_version specified, so try all grammars. return [ # Python 3.7-3.9 pygram.python_grammar_async_keywords, # Python 3.0-3.6 pygram.python_grammar, # Python 3.10+ pygram.python_grammar_soft_keywords, ] grammars = [] # If we have to parse both, try to parse async as a keyword first if not supports_feature( target_versions, Feature.ASYNC_IDENTIFIERS ) and not supports_feature(target_versions, Feature.PATTERN_MATCHING): # Python 3.7-3.9 grammars.append(pygram.python_grammar_async_keywords) if not supports_feature(target_versions, Feature.ASYNC_KEYWORDS): # Python 3.0-3.6 grammars.append(pygram.python_grammar) if any(Feature.PATTERN_MATCHING in VERSION_TO_FEATURES[v] for v in target_versions): # Python 3.10+ grammars.append(pygram.python_grammar_soft_keywords) # At least one of the above branches must have been taken, because every Python # version has exactly one of the two 'ASYNC_*' flags return grammars def lib2to3_parse( src_txt: str, target_versions: Collection[TargetVersion] = () ) -> Node: """Given a string with source, return the lib2to3 Node.""" if not src_txt.endswith("\n"): src_txt += "\n" grammars = get_grammars(set(target_versions)) if target_versions: max_tv = max(target_versions, key=lambda tv: tv.value) tv_str = f" for target version {max_tv.pretty()}" else: tv_str = "" errors = {} for grammar in grammars: drv = driver.Driver(grammar) try: result = drv.parse_string(src_txt, False) break except ParseError as pe: lineno, column = pe.context[1] lines = src_txt.splitlines() try: faulty_line = lines[lineno - 1] except IndexError: faulty_line = "<line number missing in source>" errors[grammar.version] = InvalidInput( f"Cannot parse{tv_str}: {lineno}:{column}: {faulty_line}" ) except TokenError as te: # In edge cases these are raised; and typically don't have a "faulty_line". lineno, column = te.args[1] errors[grammar.version] = InvalidInput( f"Cannot parse{tv_str}: {lineno}:{column}: {te.args[0]}" ) else: # Choose the latest version when raising the actual parsing error. assert len(errors) >= 1 exc = errors[max(errors)] raise exc from None if isinstance(result, Leaf): result = Node(syms.file_input, [result]) return result def matches_grammar(src_txt: str, grammar: Grammar) -> bool: drv = driver.Driver(grammar) try: drv.parse_string(src_txt, False) except (ParseError, TokenError, IndentationError): return False else: return True def lib2to3_unparse(node: Node) -> str: """Given a lib2to3 node, return its string representation.""" code = str(node) return code class ASTSafetyError(Exception): """Raised when Black's generated code is not equivalent to the old AST.""" def _parse_single_version( src: str, version: tuple[int, int], *, type_comments: bool ) -> ast.AST: filename = "<unknown>" with warnings.catch_warnings(): warnings.simplefilter("ignore", SyntaxWarning) warnings.simplefilter("ignore", DeprecationWarning) return ast.parse( src, filename, feature_version=version, type_comments=type_comments ) def parse_ast(src: str) -> ast.AST: # TODO: support Python 4+ ;) versions = [(3, minor) for minor in range(3, sys.version_info[1] + 1)] first_error = "" for version in sorted(versions, reverse=True): try: return _parse_single_version(src, version, type_comments=True) except SyntaxError as e: if not first_error: first_error = str(e) # Try to parse without type comments for version in sorted(versions, reverse=True): try: return _parse_single_version(src, version, type_comments=False) except SyntaxError: pass raise SyntaxError(first_error) def _normalize(lineend: str, value: str) -> str: # To normalize, we strip any leading and trailing space from # each line... stripped: list[str] = [i.strip() for i in value.splitlines()] normalized = lineend.join(stripped) # ...and remove any blank lines at the beginning and end of # the whole string return normalized.strip() def stringify_ast(node: ast.AST) -> Iterator[str]: """Simple visitor generating strings to compare ASTs by content.""" return _stringify_ast(node, []) def _stringify_ast_with_new_parent( node: ast.AST, parent_stack: list[ast.AST], new_parent: ast.AST ) -> Iterator[str]: parent_stack.append(new_parent) yield from _stringify_ast(node, parent_stack) parent_stack.pop() def _stringify_ast(node: ast.AST, parent_stack: list[ast.AST]) -> Iterator[str]: if ( isinstance(node, ast.Constant) and isinstance(node.value, str) and node.kind == "u" ): # It's a quirk of history that we strip the u prefix over here. We used to # rewrite the AST nodes for Python version compatibility and we never copied # over the kind node.kind = None yield f"{' ' * len(parent_stack)}{node.__class__.__name__}(" for field in sorted(node._fields): # TypeIgnore has only one field 'lineno' which breaks this comparison if isinstance(node, ast.TypeIgnore): break try: value: object = getattr(node, field) except AttributeError: continue yield f"{' ' * (len(parent_stack) + 1)}{field}=" if isinstance(value, list): for item in value: # Ignore nested tuples within del statements, because we may insert # parentheses and they change the AST. if ( field == "targets" and isinstance(node, ast.Delete) and isinstance(item, ast.Tuple) ): for elt in _unwrap_tuples(item): yield from _stringify_ast_with_new_parent( elt, parent_stack, node ) elif isinstance(item, ast.AST): yield from _stringify_ast_with_new_parent(item, parent_stack, node) elif isinstance(value, ast.AST): yield from _stringify_ast_with_new_parent(value, parent_stack, node) else: normalized: object if ( isinstance(node, ast.Constant) and field == "value" and isinstance(value, str) and len(parent_stack) >= 2 # Any standalone string, ideally this would # exactly match black.nodes.is_docstring and isinstance(parent_stack[-1], ast.Expr) ): # Constant strings may be indented across newlines, if they are # docstrings; fold spaces after newlines when comparing. Similarly, # trailing and leading space may be removed. normalized = _normalize("\n", value) elif field == "type_comment" and isinstance(value, str): # Trailing whitespace in type comments is removed. normalized = value.rstrip() else: normalized = value yield ( f"{' ' * (len(parent_stack) + 1)}{normalized!r}, #" f" {value.__class__.__name__}" ) yield f"{' ' * len(parent_stack)}) # /{node.__class__.__name__}" def _unwrap_tuples(node: ast.Tuple) -> Iterator[ast.AST]: for elt in node.elts: if isinstance(elt, ast.Tuple): yield from _unwrap_tuples(elt) else: yield elt
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/src/black/strings.py
src/black/strings.py
""" Simple formatting on strings. Further string formatting code is in trans.py. """ import re import sys from functools import lru_cache from re import Match, Pattern from typing import Final from black._width_table import WIDTH_TABLE from blib2to3.pytree import Leaf STRING_PREFIX_CHARS: Final = "fturbFTURB" # All possible string prefix characters. STRING_PREFIX_RE: Final = re.compile( r"^([" + STRING_PREFIX_CHARS + r"]*)(.*)$", re.DOTALL ) UNICODE_ESCAPE_RE: Final = re.compile( r"(?P<backslashes>\\+)(?P<body>" r"(u(?P<u>[a-fA-F0-9]{4}))" # Character with 16-bit hex value xxxx r"|(U(?P<U>[a-fA-F0-9]{8}))" # Character with 32-bit hex value xxxxxxxx r"|(x(?P<x>[a-fA-F0-9]{2}))" # Character with hex value hh r"|(N\{(?P<N>[a-zA-Z0-9 \-]{2,})\})" # Character named name in the Unicode database r")", re.VERBOSE, ) def sub_twice(regex: Pattern[str], replacement: str, original: str) -> str: """Replace `regex` with `replacement` twice on `original`. This is used by string normalization to perform replaces on overlapping matches. """ return regex.sub(replacement, regex.sub(replacement, original)) def has_triple_quotes(string: str) -> bool: """ Returns: True iff @string starts with three quotation characters. """ raw_string = string.lstrip(STRING_PREFIX_CHARS) return raw_string[:3] in {'"""', "'''"} def lines_with_leading_tabs_expanded(s: str) -> list[str]: """ Splits string into lines and expands only leading tabs (following the normal Python rules) """ lines = [] for line in s.splitlines(): stripped_line = line.lstrip() if not stripped_line or stripped_line == line: lines.append(line) else: prefix_length = len(line) - len(stripped_line) prefix = line[:prefix_length].expandtabs() lines.append(prefix + stripped_line) if s.endswith("\n"): lines.append("") return lines def fix_multiline_docstring(docstring: str, prefix: str) -> str: # https://www.python.org/dev/peps/pep-0257/#handling-docstring-indentation assert docstring, "INTERNAL ERROR: Multiline docstrings cannot be empty" lines = lines_with_leading_tabs_expanded(docstring) # Determine minimum indentation (first line doesn't count): indent = sys.maxsize for line in lines[1:]: stripped = line.lstrip() if stripped: indent = min(indent, len(line) - len(stripped)) # Remove indentation (first line is special): trimmed = [lines[0].strip()] if indent < sys.maxsize: last_line_idx = len(lines) - 2 for i, line in enumerate(lines[1:]): stripped_line = line[indent:].rstrip() if stripped_line or i == last_line_idx: trimmed.append(prefix + stripped_line) else: trimmed.append("") return "\n".join(trimmed) def get_string_prefix(string: str) -> str: """ Pre-conditions: * assert_is_leaf_string(@string) Returns: @string's prefix (e.g. '', 'r', 'f', or 'rf'). """ assert_is_leaf_string(string) prefix = [] for char in string: if char in STRING_PREFIX_CHARS: prefix.append(char) else: break return "".join(prefix) def assert_is_leaf_string(string: str) -> None: """ Checks the pre-condition that @string has the format that you would expect of `leaf.value` where `leaf` is some Leaf such that `leaf.type == token.STRING`. A more precise description of the pre-conditions that are checked are listed below. Pre-conditions: * @string starts with either ', ", <prefix>', or <prefix>" where `set(<prefix>)` is some subset of `set(STRING_PREFIX_CHARS)`. * @string ends with a quote character (' or "). Raises: AssertionError(...) if the pre-conditions listed above are not satisfied. """ dquote_idx = string.find('"') squote_idx = string.find("'") if -1 in [dquote_idx, squote_idx]: quote_idx = max(dquote_idx, squote_idx) else: quote_idx = min(squote_idx, dquote_idx) assert ( 0 <= quote_idx < len(string) - 1 ), f"{string!r} is missing a starting quote character (' or \")." assert string[-1] in ( "'", '"', ), f"{string!r} is missing an ending quote character (' or \")." assert set(string[:quote_idx]).issubset( set(STRING_PREFIX_CHARS) ), f"{set(string[:quote_idx])} is NOT a subset of {set(STRING_PREFIX_CHARS)}." def normalize_string_prefix(s: str) -> str: """Make all string prefixes lowercase.""" match = STRING_PREFIX_RE.match(s) assert match is not None, f"failed to match string {s!r}" orig_prefix = match.group(1) new_prefix = ( orig_prefix.replace("F", "f") .replace("B", "b") .replace("U", "") .replace("u", "") ) # Python syntax guarantees max 2 prefixes and that one of them is "r" if len(new_prefix) == 2 and new_prefix[0].lower() != "r": new_prefix = new_prefix[::-1] return f"{new_prefix}{match.group(2)}" # Re(gex) does actually cache patterns internally but this still improves # performance on a long list literal of strings by 5-9% since lru_cache's # caching overhead is much lower. @lru_cache(maxsize=64) def _cached_compile(pattern: str) -> Pattern[str]: return re.compile(pattern) def normalize_string_quotes(s: str) -> str: """Prefer double quotes but only if it doesn't cause more escaping. Adds or removes backslashes as appropriate. """ value = s.lstrip(STRING_PREFIX_CHARS) if value[:3] == '"""': return s elif value[:3] == "'''": orig_quote = "'''" new_quote = '"""' elif value[0] == '"': orig_quote = '"' new_quote = "'" else: orig_quote = "'" new_quote = '"' first_quote_pos = s.find(orig_quote) assert first_quote_pos != -1, f"INTERNAL ERROR: Malformed string {s!r}" prefix = s[:first_quote_pos] unescaped_new_quote = _cached_compile(rf"(([^\\]|^)(\\\\)*){new_quote}") escaped_new_quote = _cached_compile(rf"([^\\]|^)\\((?:\\\\)*){new_quote}") escaped_orig_quote = _cached_compile(rf"([^\\]|^)\\((?:\\\\)*){orig_quote}") body = s[first_quote_pos + len(orig_quote) : -len(orig_quote)] if "r" in prefix.casefold(): if unescaped_new_quote.search(body): # There's at least one unescaped new_quote in this raw string # so converting is impossible return s # Do not introduce or remove backslashes in raw strings new_body = body else: # remove unnecessary escapes new_body = sub_twice(escaped_new_quote, rf"\1\2{new_quote}", body) if body != new_body: # Consider the string without unnecessary escapes as the original body = new_body s = f"{prefix}{orig_quote}{body}{orig_quote}" new_body = sub_twice(escaped_orig_quote, rf"\1\2{orig_quote}", new_body) new_body = sub_twice(unescaped_new_quote, rf"\1\\{new_quote}", new_body) if "f" in prefix.casefold(): matches = re.findall( r""" (?:(?<!\{)|^)\{ # start of the string or a non-{ followed by a single { ([^{].*?) # contents of the brackets except if begins with {{ \}(?:(?!\})|$) # A } followed by end of the string or a non-} """, new_body, re.VERBOSE, ) for m in matches: if "\\" in str(m): # Do not introduce backslashes in interpolated expressions return s if new_quote == '"""' and new_body[-1:] == '"': # edge case: new_body = new_body[:-1] + '\\"' orig_escape_count = body.count("\\") new_escape_count = new_body.count("\\") if new_escape_count > orig_escape_count: return s # Do not introduce more escaping if new_escape_count == orig_escape_count and orig_quote == '"': return s # Prefer double quotes return f"{prefix}{new_quote}{new_body}{new_quote}" def normalize_fstring_quotes( quote: str, middles: list[Leaf], is_raw_fstring: bool, ) -> tuple[list[Leaf], str]: """Prefer double quotes but only if it doesn't cause more escaping. Adds or removes backslashes as appropriate. """ if quote == '"""': return middles, quote elif quote == "'''": new_quote = '"""' elif quote == '"': new_quote = "'" else: new_quote = '"' unescaped_new_quote = _cached_compile(rf"(([^\\]|^)(\\\\)*){new_quote}") escaped_new_quote = _cached_compile(rf"([^\\]|^)\\((?:\\\\)*){new_quote}") escaped_orig_quote = _cached_compile(rf"([^\\]|^)\\((?:\\\\)*){quote}") if is_raw_fstring: for middle in middles: if unescaped_new_quote.search(middle.value): # There's at least one unescaped new_quote in this raw string # so converting is impossible return middles, quote # Do not introduce or remove backslashes in raw strings, just use double quote return middles, '"' new_segments = [] for middle in middles: segment = middle.value # remove unnecessary escapes new_segment = sub_twice(escaped_new_quote, rf"\1\2{new_quote}", segment) if segment != new_segment: # Consider the string without unnecessary escapes as the original middle.value = new_segment new_segment = sub_twice(escaped_orig_quote, rf"\1\2{quote}", new_segment) new_segment = sub_twice(unescaped_new_quote, rf"\1\\{new_quote}", new_segment) new_segments.append(new_segment) if new_quote == '"""' and new_segments[-1].endswith('"'): # edge case: new_segments[-1] = new_segments[-1][:-1] + '\\"' for middle, new_segment in zip(middles, new_segments, strict=True): orig_escape_count = middle.value.count("\\") new_escape_count = new_segment.count("\\") if new_escape_count > orig_escape_count: return middles, quote # Do not introduce more escaping if new_escape_count == orig_escape_count and quote == '"': return middles, quote # Prefer double quotes for middle, new_segment in zip(middles, new_segments, strict=True): middle.value = new_segment return middles, new_quote def normalize_unicode_escape_sequences(leaf: Leaf) -> None: """Replace hex codes in Unicode escape sequences with lowercase representation.""" text = leaf.value prefix = get_string_prefix(text) if "r" in prefix.lower(): return def replace(m: Match[str]) -> str: groups = m.groupdict() back_slashes = groups["backslashes"] if len(back_slashes) % 2 == 0: return back_slashes + groups["body"] if groups["u"]: # \u return back_slashes + "u" + groups["u"].lower() elif groups["U"]: # \U return back_slashes + "U" + groups["U"].lower() elif groups["x"]: # \x return back_slashes + "x" + groups["x"].lower() else: assert groups["N"], f"Unexpected match: {m}" # \N{} return back_slashes + "N{" + groups["N"].upper() + "}" leaf.value = re.sub(UNICODE_ESCAPE_RE, replace, text) @lru_cache(maxsize=4096) def char_width(char: str) -> int: """Return the width of a single character as it would be displayed in a terminal or editor (which respects Unicode East Asian Width). Full width characters are counted as 2, while half width characters are counted as 1. Also control characters are counted as 0. """ table = WIDTH_TABLE codepoint = ord(char) highest = len(table) - 1 lowest = 0 idx = highest // 2 while True: start_codepoint, end_codepoint, width = table[idx] if codepoint < start_codepoint: highest = idx - 1 elif codepoint > end_codepoint: lowest = idx + 1 else: return 0 if width < 0 else width if highest < lowest: break idx = (highest + lowest) // 2 return 1 def str_width(line_str: str) -> int: """Return the width of `line_str` as it would be displayed in a terminal or editor (which respects Unicode East Asian Width). You could utilize this function to determine, for example, if a string is too wide to display in a terminal or editor. """ if line_str.isascii(): # Fast path for a line consisting of only ASCII characters return len(line_str) return sum(map(char_width, line_str)) def count_chars_in_width(line_str: str, max_width: int) -> int: """Count the number of characters in `line_str` that would fit in a terminal or editor of `max_width` (which respects Unicode East Asian Width). """ total_width = 0 for i, char in enumerate(line_str): width = char_width(char) if width + total_width > max_width: return i total_width += width return len(line_str)
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/src/black/comments.py
src/black/comments.py
import re from collections.abc import Collection, Iterator from dataclasses import dataclass from functools import lru_cache from typing import Final, Union from black.mode import Mode, Preview from black.nodes import ( CLOSING_BRACKETS, STANDALONE_COMMENT, STATEMENT, WHITESPACE, container_of, first_leaf_of, is_type_comment_string, make_simple_prefix, preceding_leaf, syms, ) from blib2to3.pgen2 import token from blib2to3.pytree import Leaf, Node # types LN = Union[Leaf, Node] FMT_OFF: Final = {"# fmt: off", "# fmt:off", "# yapf: disable"} FMT_SKIP: Final = {"# fmt: skip", "# fmt:skip"} FMT_ON: Final = {"# fmt: on", "# fmt:on", "# yapf: enable"} # Compound statements we care about for fmt: skip handling # (excludes except_clause and case_block which aren't standalone compound statements) _COMPOUND_STATEMENTS: Final = STATEMENT - {syms.except_clause, syms.case_block} COMMENT_EXCEPTIONS = " !:#'" _COMMENT_PREFIX = "# " _COMMENT_LIST_SEPARATOR = ";" @dataclass class ProtoComment: """Describes a piece of syntax that is a comment. It's not a :class:`blib2to3.pytree.Leaf` so that: * it can be cached (`Leaf` objects should not be reused more than once as they store their lineno, column, prefix, and parent information); * `newlines` and `consumed` fields are kept separate from the `value`. This simplifies handling of special marker comments like ``# fmt: off/on``. """ type: int # token.COMMENT or STANDALONE_COMMENT value: str # content of the comment newlines: int # how many newlines before the comment consumed: int # how many characters of the original leaf's prefix did we consume form_feed: bool # is there a form feed before the comment leading_whitespace: str # leading whitespace before the comment, if any def generate_comments(leaf: LN, mode: Mode) -> Iterator[Leaf]: """Clean the prefix of the `leaf` and generate comments from it, if any. Comments in lib2to3 are shoved into the whitespace prefix. This happens in `pgen2/driver.py:Driver.parse_tokens()`. This was a brilliant implementation move because it does away with modifying the grammar to include all the possible places in which comments can be placed. The sad consequence for us though is that comments don't "belong" anywhere. This is why this function generates simple parentless Leaf objects for comments. We simply don't know what the correct parent should be. No matter though, we can live without this. We really only need to differentiate between inline and standalone comments. The latter don't share the line with any code. Inline comments are emitted as regular token.COMMENT leaves. Standalone are emitted with a fake STANDALONE_COMMENT token identifier. """ total_consumed = 0 for pc in list_comments( leaf.prefix, is_endmarker=leaf.type == token.ENDMARKER, mode=mode ): total_consumed = pc.consumed prefix = make_simple_prefix(pc.newlines, pc.form_feed) yield Leaf(pc.type, pc.value, prefix=prefix) normalize_trailing_prefix(leaf, total_consumed) @lru_cache(maxsize=4096) def list_comments(prefix: str, *, is_endmarker: bool, mode: Mode) -> list[ProtoComment]: """Return a list of :class:`ProtoComment` objects parsed from the given `prefix`.""" result: list[ProtoComment] = [] if not prefix or "#" not in prefix: return result consumed = 0 nlines = 0 ignored_lines = 0 form_feed = False for index, full_line in enumerate(re.split("\r?\n|\r", prefix)): consumed += len(full_line) + 1 # adding the length of the split '\n' match = re.match(r"^(\s*)(\S.*|)$", full_line) assert match whitespace, line = match.groups() if not line: nlines += 1 if "\f" in full_line: form_feed = True if not line.startswith("#"): # Escaped newlines outside of a comment are not really newlines at # all. We treat a single-line comment following an escaped newline # as a simple trailing comment. if line.endswith("\\"): ignored_lines += 1 continue if index == ignored_lines and not is_endmarker: comment_type = token.COMMENT # simple trailing comment else: comment_type = STANDALONE_COMMENT comment = make_comment(line, mode=mode) result.append( ProtoComment( type=comment_type, value=comment, newlines=nlines, consumed=consumed, form_feed=form_feed, leading_whitespace=whitespace, ) ) form_feed = False nlines = 0 return result def normalize_trailing_prefix(leaf: LN, total_consumed: int) -> None: """Normalize the prefix that's left over after generating comments. Note: don't use backslashes for formatting or you'll lose your voting rights. """ remainder = leaf.prefix[total_consumed:] if "\\" not in remainder: nl_count = remainder.count("\n") form_feed = "\f" in remainder and remainder.endswith("\n") leaf.prefix = make_simple_prefix(nl_count, form_feed) return leaf.prefix = "" def make_comment(content: str, mode: Mode) -> str: """Return a consistently formatted comment from the given `content` string. All comments (except for "##", "#!", "#:", '#'") should have a single space between the hash sign and the content. If `content` didn't start with a hash sign, one is provided. Comments containing fmt directives are preserved exactly as-is to respect user intent (e.g., `#no space # fmt: skip` stays as-is). """ content = content.rstrip() if not content: return "#" # Preserve comments with fmt directives exactly as-is if content.startswith("#") and contains_fmt_directive(content): return content if content[0] == "#": content = content[1:] if ( content and content[0] == "\N{NO-BREAK SPACE}" and not is_type_comment_string("# " + content.lstrip(), mode=mode) ): content = " " + content[1:] # Replace NBSP by a simple space if ( Preview.standardize_type_comments in mode and content and "\N{NO-BREAK SPACE}" not in content and is_type_comment_string("#" + content, mode=mode) ): type_part, value_part = content.split(":", 1) content = type_part.strip() + ": " + value_part.strip() if content and content[0] not in COMMENT_EXCEPTIONS: content = " " + content return "#" + content def normalize_fmt_off( node: Node, mode: Mode, lines: Collection[tuple[int, int]] ) -> None: """Convert content between `# fmt: off`/`# fmt: on` into standalone comments.""" try_again = True while try_again: try_again = convert_one_fmt_off_pair(node, mode, lines) def _should_process_fmt_comment( comment: ProtoComment, leaf: Leaf ) -> tuple[bool, bool, bool]: """Check if comment should be processed for fmt handling. Returns (should_process, is_fmt_off, is_fmt_skip). """ is_fmt_off = contains_fmt_directive(comment.value, FMT_OFF) is_fmt_skip = contains_fmt_directive(comment.value, FMT_SKIP) if not is_fmt_off and not is_fmt_skip: return False, False, False # Invalid use when `# fmt: off` is applied before a closing bracket if is_fmt_off and leaf.type in CLOSING_BRACKETS: return False, False, False return True, is_fmt_off, is_fmt_skip def _is_valid_standalone_fmt_comment( comment: ProtoComment, leaf: Leaf, is_fmt_off: bool, is_fmt_skip: bool ) -> bool: """Check if comment is a valid standalone fmt directive. We only want standalone comments. If there's no previous leaf or if the previous leaf is indentation, it's a standalone comment in disguise. """ if comment.type == STANDALONE_COMMENT: return True prev = preceding_leaf(leaf) if not prev: return True # Treat STANDALONE_COMMENT nodes as whitespace for check if is_fmt_off and prev.type not in WHITESPACE and prev.type != STANDALONE_COMMENT: return False if is_fmt_skip and prev.type in WHITESPACE: return False return True def _handle_comment_only_fmt_block( leaf: Leaf, comment: ProtoComment, previous_consumed: int, mode: Mode, ) -> bool: """Handle fmt:off/on blocks that contain only comments. Returns True if a block was converted, False otherwise. """ all_comments = list_comments(leaf.prefix, is_endmarker=False, mode=mode) # Find the first fmt:off and its matching fmt:on fmt_off_idx = None fmt_on_idx = None for idx, c in enumerate(all_comments): if fmt_off_idx is None and contains_fmt_directive(c.value, FMT_OFF): fmt_off_idx = idx if ( fmt_off_idx is not None and idx > fmt_off_idx and contains_fmt_directive(c.value, FMT_ON) ): fmt_on_idx = idx break # Only proceed if we found both directives if fmt_on_idx is None or fmt_off_idx is None: return False comment = all_comments[fmt_off_idx] fmt_on_comment = all_comments[fmt_on_idx] original_prefix = leaf.prefix # Build the hidden value start_pos = comment.consumed end_pos = fmt_on_comment.consumed content_between_and_fmt_on = original_prefix[start_pos:end_pos] hidden_value = comment.value + "\n" + content_between_and_fmt_on if hidden_value.endswith("\n"): hidden_value = hidden_value[:-1] # Build the standalone comment prefix - preserve all content before fmt:off # including any comments that precede it if fmt_off_idx == 0: # No comments before fmt:off, use previous_consumed pre_fmt_off_consumed = previous_consumed else: # Use the consumed position of the last comment before fmt:off # This preserves all comments and content before the fmt:off directive pre_fmt_off_consumed = all_comments[fmt_off_idx - 1].consumed standalone_comment_prefix = ( original_prefix[:pre_fmt_off_consumed] + "\n" * comment.newlines ) fmt_off_prefix = original_prefix.split(comment.value)[0] if "\n" in fmt_off_prefix: fmt_off_prefix = fmt_off_prefix.split("\n")[-1] standalone_comment_prefix += fmt_off_prefix # Update leaf prefix leaf.prefix = original_prefix[fmt_on_comment.consumed :] # Insert the STANDALONE_COMMENT parent = leaf.parent assert parent is not None, "INTERNAL ERROR: fmt: on/off handling (prefix only)" leaf_idx = None for idx, child in enumerate(parent.children): if child is leaf: leaf_idx = idx break assert leaf_idx is not None, "INTERNAL ERROR: fmt: on/off handling (leaf index)" parent.insert_child( leaf_idx, Leaf( STANDALONE_COMMENT, hidden_value, prefix=standalone_comment_prefix, fmt_pass_converted_first_leaf=None, ), ) return True def convert_one_fmt_off_pair( node: Node, mode: Mode, lines: Collection[tuple[int, int]] ) -> bool: """Convert content of a single `# fmt: off`/`# fmt: on` into a standalone comment. Returns True if a pair was converted. """ for leaf in node.leaves(): # Skip STANDALONE_COMMENT nodes that were created by fmt:off/on/skip processing # to avoid reprocessing them in subsequent iterations if leaf.type == STANDALONE_COMMENT and hasattr( leaf, "fmt_pass_converted_first_leaf" ): continue previous_consumed = 0 for comment in list_comments(leaf.prefix, is_endmarker=False, mode=mode): should_process, is_fmt_off, is_fmt_skip = _should_process_fmt_comment( comment, leaf ) if not should_process: previous_consumed = comment.consumed continue if not _is_valid_standalone_fmt_comment( comment, leaf, is_fmt_off, is_fmt_skip ): previous_consumed = comment.consumed continue ignored_nodes = list(generate_ignored_nodes(leaf, comment, mode)) # Handle comment-only blocks if not ignored_nodes and is_fmt_off: if _handle_comment_only_fmt_block( leaf, comment, previous_consumed, mode ): return True continue # Need actual nodes to process if not ignored_nodes: continue # Handle regular fmt blocks _handle_regular_fmt_block( ignored_nodes, comment, previous_consumed, is_fmt_skip, lines, leaf, ) return True return False def _handle_regular_fmt_block( ignored_nodes: list[LN], comment: ProtoComment, previous_consumed: int, is_fmt_skip: bool, lines: Collection[tuple[int, int]], leaf: Leaf, ) -> None: """Handle fmt blocks with actual AST nodes.""" first = ignored_nodes[0] # Can be a container node with the `leaf`. parent = first.parent prefix = first.prefix if contains_fmt_directive(comment.value, FMT_OFF): first.prefix = prefix[comment.consumed :] if is_fmt_skip: first.prefix = "" standalone_comment_prefix = prefix else: standalone_comment_prefix = prefix[:previous_consumed] + "\n" * comment.newlines # Ensure STANDALONE_COMMENT nodes have trailing newlines when stringified # This prevents multiple fmt: skip comments from being concatenated on one line parts = [] for node in ignored_nodes: if isinstance(node, Leaf) and node.type == STANDALONE_COMMENT: # Add newline after STANDALONE_COMMENT Leaf node_str = str(node) if not node_str.endswith("\n"): node_str += "\n" parts.append(node_str) elif isinstance(node, Node): # For nodes that might contain STANDALONE_COMMENT leaves, # we need custom stringify has_standalone = any( leaf.type == STANDALONE_COMMENT for leaf in node.leaves() ) if has_standalone: # Stringify node with STANDALONE_COMMENT leaves having trailing newlines def stringify_node(n: LN) -> str: if isinstance(n, Leaf): if n.type == STANDALONE_COMMENT: result = n.prefix + n.value if not result.endswith("\n"): result += "\n" return result return str(n) else: # For nested nodes, recursively process children return "".join(stringify_node(child) for child in n.children) parts.append(stringify_node(node)) else: parts.append(str(node)) else: parts.append(str(node)) hidden_value = "".join(parts) comment_lineno = leaf.lineno - comment.newlines if contains_fmt_directive(comment.value, FMT_OFF): fmt_off_prefix = "" if len(lines) > 0 and not any( line[0] <= comment_lineno <= line[1] for line in lines ): # keeping indentation of comment by preserving original whitespaces. fmt_off_prefix = prefix.split(comment.value)[0] if "\n" in fmt_off_prefix: fmt_off_prefix = fmt_off_prefix.split("\n")[-1] standalone_comment_prefix += fmt_off_prefix hidden_value = comment.value + "\n" + hidden_value if is_fmt_skip: hidden_value += comment.leading_whitespace + comment.value if hidden_value.endswith("\n"): # That happens when one of the `ignored_nodes` ended with a NEWLINE # leaf (possibly followed by a DEDENT). hidden_value = hidden_value[:-1] first_idx: int | None = None for ignored in ignored_nodes: index = ignored.remove() if first_idx is None: first_idx = index assert parent is not None, "INTERNAL ERROR: fmt: on/off handling (1)" assert first_idx is not None, "INTERNAL ERROR: fmt: on/off handling (2)" parent.insert_child( first_idx, Leaf( STANDALONE_COMMENT, hidden_value, prefix=standalone_comment_prefix, fmt_pass_converted_first_leaf=first_leaf_of(first), ), ) def generate_ignored_nodes( leaf: Leaf, comment: ProtoComment, mode: Mode ) -> Iterator[LN]: """Starting from the container of `leaf`, generate all leaves until `# fmt: on`. If comment is skip, returns leaf only. Stops at the end of the block. """ if contains_fmt_directive(comment.value, FMT_SKIP): yield from _generate_ignored_nodes_from_fmt_skip(leaf, comment, mode) return container: LN | None = container_of(leaf) while container is not None and container.type != token.ENDMARKER: if is_fmt_on(container, mode=mode): return # fix for fmt: on in children if children_contains_fmt_on(container, mode=mode): for index, child in enumerate(container.children): if isinstance(child, Leaf) and is_fmt_on(child, mode=mode): if child.type in CLOSING_BRACKETS: # This means `# fmt: on` is placed at a different bracket level # than `# fmt: off`. This is an invalid use, but as a courtesy, # we include this closing bracket in the ignored nodes. # The alternative is to fail the formatting. yield child return if ( child.type == token.INDENT and index < len(container.children) - 1 and children_contains_fmt_on( container.children[index + 1], mode=mode ) ): # This means `# fmt: on` is placed right after an indentation # level, and we shouldn't swallow the previous INDENT token. return if children_contains_fmt_on(child, mode=mode): return yield child else: if container.type == token.DEDENT and container.next_sibling is None: # This can happen when there is no matching `# fmt: on` comment at the # same level as `# fmt: on`. We need to keep this DEDENT. return yield container container = container.next_sibling def _find_compound_statement_context(parent: Node) -> Node | None: """Return the body node of a compound statement if we should respect fmt: skip. This handles one-line compound statements like: if condition: body # fmt: skip When Black expands such statements, they temporarily look like: if condition: body # fmt: skip In both cases, we want to return the body node (either the simple_stmt directly or the suite containing it). """ if parent.type != syms.simple_stmt: return None if not isinstance(parent.parent, Node): return None # Case 1: Expanded form after Black's initial formatting pass. # The one-liner has been split across multiple lines: # if True: # print("a"); print("b") # fmt: skip # Structure: compound_stmt -> suite -> simple_stmt if ( parent.parent.type == syms.suite and isinstance(parent.parent.parent, Node) and parent.parent.parent.type in _COMPOUND_STATEMENTS ): return parent.parent # Case 2: Original one-line form from the input source. # The statement is still on a single line: # if True: print("a"); print("b") # fmt: skip # Structure: compound_stmt -> simple_stmt if parent.parent.type in _COMPOUND_STATEMENTS: return parent return None def _should_keep_compound_statement_inline( body_node: Node, simple_stmt_parent: Node ) -> bool: """Check if a compound statement should be kept on one line. Returns True only for compound statements with semicolon-separated bodies, like: if True: print("a"); print("b") # fmt: skip """ # Check if there are semicolons in the body for leaf in body_node.leaves(): if leaf.type == token.SEMI: # Verify it's a single-line body (one simple_stmt) if body_node.type == syms.suite: # After formatting: check suite has one simple_stmt child simple_stmts = [ child for child in body_node.children if child.type == syms.simple_stmt ] return len(simple_stmts) == 1 and simple_stmts[0] is simple_stmt_parent else: # Original form: body_node IS the simple_stmt return body_node is simple_stmt_parent return False def _get_compound_statement_header( body_node: Node, simple_stmt_parent: Node ) -> list[LN]: """Get header nodes for a compound statement that should be preserved inline.""" if not _should_keep_compound_statement_inline(body_node, simple_stmt_parent): return [] # Get the compound statement (parent of body) compound_stmt = body_node.parent if compound_stmt is None or compound_stmt.type not in _COMPOUND_STATEMENTS: return [] # Collect all header leaves before the body header_leaves: list[LN] = [] for child in compound_stmt.children: if child is body_node: break if isinstance(child, Leaf): if child.type not in (token.NEWLINE, token.INDENT): header_leaves.append(child) else: header_leaves.extend(child.leaves()) return header_leaves def _generate_ignored_nodes_from_fmt_skip( leaf: Leaf, comment: ProtoComment, mode: Mode ) -> Iterator[LN]: """Generate all leaves that should be ignored by the `# fmt: skip` from `leaf`.""" prev_sibling = leaf.prev_sibling parent = leaf.parent ignored_nodes: list[LN] = [] # Need to properly format the leaf prefix to compare it to comment.value, # which is also formatted comments = list_comments(leaf.prefix, is_endmarker=False, mode=mode) if not comments or comment.value != comments[0].value: return if Preview.fix_fmt_skip_in_one_liners in mode and not prev_sibling and parent: prev_sibling = parent.prev_sibling if prev_sibling is not None: leaf.prefix = leaf.prefix[comment.consumed :] if Preview.fix_fmt_skip_in_one_liners not in mode: siblings = [prev_sibling] while ( "\n" not in prev_sibling.prefix and prev_sibling.prev_sibling is not None ): prev_sibling = prev_sibling.prev_sibling siblings.insert(0, prev_sibling) yield from siblings return # Generates the nodes to be ignored by `fmt: skip`. # Nodes to ignore are the ones on the same line as the # `# fmt: skip` comment, excluding the `# fmt: skip` # node itself. # Traversal process (starting at the `# fmt: skip` node): # 1. Move to the `prev_sibling` of the current node. # 2. If `prev_sibling` has children, go to its rightmost leaf. # 3. If there's no `prev_sibling`, move up to the parent # node and repeat. # 4. Continue until: # a. You encounter an `INDENT` or `NEWLINE` node (indicates # start of the line). # b. You reach the root node. # Include all visited LEAVES in the ignored list, except INDENT # or NEWLINE leaves. current_node = prev_sibling ignored_nodes = [current_node] if current_node.prev_sibling is None and current_node.parent is not None: current_node = current_node.parent # Track seen nodes to detect cycles that can occur after tree modifications seen_nodes = {id(current_node)} while "\n" not in current_node.prefix and current_node.prev_sibling is not None: leaf_nodes = list(current_node.prev_sibling.leaves()) next_node = leaf_nodes[-1] if leaf_nodes else current_node # Detect infinite loop - if we've seen this node before, stop # This can happen when STANDALONE_COMMENT nodes are inserted # during processing if id(next_node) in seen_nodes: break current_node = next_node seen_nodes.add(id(current_node)) # Stop if we encounter a STANDALONE_COMMENT created by fmt processing if ( isinstance(current_node, Leaf) and current_node.type == STANDALONE_COMMENT and hasattr(current_node, "fmt_pass_converted_first_leaf") ): break if ( current_node.type in CLOSING_BRACKETS and current_node.parent and current_node.parent.type == syms.atom ): current_node = current_node.parent if current_node.type in (token.NEWLINE, token.INDENT): current_node.prefix = "" break if current_node.type == token.DEDENT: break # Special case for with expressions # Without this, we can stuck inside the asexpr_test's children's children if ( current_node.parent and current_node.parent.type == syms.asexpr_test and current_node.parent.parent and current_node.parent.parent.type == syms.with_stmt ): current_node = current_node.parent ignored_nodes.insert(0, current_node) if current_node.prev_sibling is None and current_node.parent is not None: current_node = current_node.parent # Special handling for compound statements with semicolon-separated bodies if Preview.fix_fmt_skip_in_one_liners in mode and isinstance(parent, Node): body_node = _find_compound_statement_context(parent) if body_node is not None: header_nodes = _get_compound_statement_header(body_node, parent) if header_nodes: ignored_nodes = header_nodes + ignored_nodes yield from ignored_nodes elif ( parent is not None and parent.type == syms.suite and leaf.type == token.NEWLINE ): # The `# fmt: skip` is on the colon line of the if/while/def/class/... # statements. The ignored nodes should be previous siblings of the # parent suite node. leaf.prefix = "" parent_sibling = parent.prev_sibling while parent_sibling is not None and parent_sibling.type != syms.suite: ignored_nodes.insert(0, parent_sibling) parent_sibling = parent_sibling.prev_sibling # Special case for `async_stmt` where the ASYNC token is on the # grandparent node. grandparent = parent.parent if ( grandparent is not None and grandparent.prev_sibling is not None and grandparent.prev_sibling.type == token.ASYNC ): ignored_nodes.insert(0, grandparent.prev_sibling) yield from iter(ignored_nodes) def is_fmt_on(container: LN, mode: Mode) -> bool: """Determine whether formatting is switched on within a container. Determined by whether the last `# fmt:` comment is `on` or `off`. """ fmt_on = False for comment in list_comments(container.prefix, is_endmarker=False, mode=mode): if contains_fmt_directive(comment.value, FMT_ON): fmt_on = True elif contains_fmt_directive(comment.value, FMT_OFF): fmt_on = False return fmt_on def children_contains_fmt_on(container: LN, mode: Mode) -> bool: """Determine if children have formatting switched on.""" for child in container.children: leaf = first_leaf_of(child) if leaf is not None and is_fmt_on(leaf, mode=mode): return True return False def contains_pragma_comment(comment_list: list[Leaf]) -> bool: """ Returns: True iff one of the comments in @comment_list is a pragma used by one of the more common static analysis tools for python (e.g. mypy, flake8, pylint). """ for comment in comment_list: if comment.value.startswith(("# type:", "# noqa", "# pylint:")): return True return False def contains_fmt_directive( comment_line: str, directives: set[str] = FMT_OFF | FMT_ON | FMT_SKIP ) -> bool: """ Checks if the given comment contains format directives, alone or paired with other comments. Defaults to checking all directives (skip, off, on, yapf), but can be narrowed to specific ones. Matching styles: # foobar <-- single comment # foobar # foobar # foobar <-- multiple comments # foobar; foobar <-- list of comments (; separated) """ semantic_comment_blocks = [ comment_line, *[ _COMMENT_PREFIX + comment.strip() for comment in comment_line.split(_COMMENT_PREFIX)[1:] ], *[ _COMMENT_PREFIX + comment.strip() for comment in comment_line.strip(_COMMENT_PREFIX).split( _COMMENT_LIST_SEPARATOR ) ], ] return any(comment in directives for comment in semantic_comment_blocks)
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/src/black/__init__.py
src/black/__init__.py
import io import json import platform import re import sys import tokenize import traceback from collections.abc import ( Collection, Generator, MutableMapping, Sequence, ) from contextlib import nullcontext from dataclasses import replace from datetime import datetime, timezone from enum import Enum from json.decoder import JSONDecodeError from pathlib import Path from re import Pattern from typing import Any import click from click.core import ParameterSource from mypy_extensions import mypyc_attr from pathspec import PathSpec from pathspec.patterns.gitwildmatch import GitWildMatchPatternError from _black_version import version as __version__ from black.cache import Cache from black.comments import normalize_fmt_off from black.const import ( DEFAULT_EXCLUDES, DEFAULT_INCLUDES, DEFAULT_LINE_LENGTH, STDIN_PLACEHOLDER, ) from black.files import ( best_effort_relative_path, find_project_root, find_pyproject_toml, find_user_pyproject_toml, gen_python_files, get_gitignore, parse_pyproject_toml, path_is_excluded, resolves_outside_root_or_cannot_stat, wrap_stream_for_windows, ) from black.handle_ipynb_magics import ( PYTHON_CELL_MAGICS, jupyter_dependencies_are_installed, mask_cell, put_trailing_semicolon_back, remove_trailing_semicolon, unmask_cell, validate_cell, ) from black.linegen import LN, LineGenerator, transform_line from black.lines import EmptyLineTracker, LinesBlock from black.mode import FUTURE_FLAG_TO_FEATURE, VERSION_TO_FEATURES, Feature from black.mode import Mode as Mode # re-exported from black.mode import Preview, TargetVersion, supports_feature from black.nodes import STARS, is_number_token, is_simple_decorator_expression, syms from black.output import color_diff, diff, dump_to_file, err, ipynb_diff, out from black.parsing import ( # noqa F401 ASTSafetyError, InvalidInput, lib2to3_parse, parse_ast, stringify_ast, ) from black.ranges import ( adjusted_lines, convert_unchanged_lines, parse_line_ranges, sanitized_lines, ) from black.report import Changed, NothingChanged, Report from blib2to3.pgen2 import token from blib2to3.pytree import Leaf, Node COMPILED = Path(__file__).suffix in (".pyd", ".so") # types FileContent = str Encoding = str NewLine = str class WriteBack(Enum): NO = 0 YES = 1 DIFF = 2 CHECK = 3 COLOR_DIFF = 4 @classmethod def from_configuration( cls, *, check: bool, diff: bool, color: bool = False ) -> "WriteBack": if check and not diff: return cls.CHECK if diff and color: return cls.COLOR_DIFF return cls.DIFF if diff else cls.YES # Legacy name, left for integrations. FileMode = Mode def read_pyproject_toml( ctx: click.Context, param: click.Parameter, value: str | None ) -> str | None: """Inject Black configuration from "pyproject.toml" into defaults in `ctx`. Returns the path to a successfully found and read configuration file, None otherwise. """ if not value: value = find_pyproject_toml( ctx.params.get("src", ()), ctx.params.get("stdin_filename", None) ) if value is None: return None try: config = parse_pyproject_toml(value) except (OSError, ValueError) as e: raise click.FileError( filename=value, hint=f"Error reading configuration file: {e}" ) from None if not config: return None else: spellcheck_pyproject_toml_keys(ctx, list(config), value) # Sanitize the values to be Click friendly. For more information please see: # https://github.com/psf/black/issues/1458 # https://github.com/pallets/click/issues/1567 config = { k: str(v) if not isinstance(v, (list, dict)) else v for k, v in config.items() } target_version = config.get("target_version") if target_version is not None and not isinstance(target_version, list): raise click.BadOptionUsage( "target-version", "Config key target-version must be a list" ) exclude = config.get("exclude") if exclude is not None and not isinstance(exclude, str): raise click.BadOptionUsage("exclude", "Config key exclude must be a string") extend_exclude = config.get("extend_exclude") if extend_exclude is not None and not isinstance(extend_exclude, str): raise click.BadOptionUsage( "extend-exclude", "Config key extend-exclude must be a string" ) line_ranges = config.get("line_ranges") if line_ranges is not None: raise click.BadOptionUsage( "line-ranges", "Cannot use line-ranges in the pyproject.toml file." ) default_map: dict[str, Any] = {} if ctx.default_map: default_map.update(ctx.default_map) default_map.update(config) ctx.default_map = default_map return value def spellcheck_pyproject_toml_keys( ctx: click.Context, config_keys: list[str], config_file_path: str ) -> None: invalid_keys: list[str] = [] available_config_options = {param.name for param in ctx.command.params} invalid_keys = [key for key in config_keys if key not in available_config_options] if invalid_keys: keys_str = ", ".join(map(repr, invalid_keys)) out( f"Invalid config keys detected: {keys_str} (in {config_file_path})", fg="red", ) def target_version_option_callback( c: click.Context, p: click.Option | click.Parameter, v: tuple[str, ...] ) -> list[TargetVersion]: """Compute the target versions from a --target-version flag. This is its own function because mypy couldn't infer the type correctly when it was a lambda, causing mypyc trouble. """ return [TargetVersion[val.upper()] for val in v] def enable_unstable_feature_callback( c: click.Context, p: click.Option | click.Parameter, v: tuple[str, ...] ) -> list[Preview]: """Compute the features from an --enable-unstable-feature flag.""" return [Preview[val] for val in v] def re_compile_maybe_verbose(regex: str) -> Pattern[str]: """Compile a regular expression string in `regex`. If it contains newlines, use verbose mode. """ if "\n" in regex: regex = "(?x)" + regex compiled: Pattern[str] = re.compile(regex) return compiled def validate_regex( ctx: click.Context, param: click.Parameter, value: str | None, ) -> Pattern[str] | None: try: return re_compile_maybe_verbose(value) if value is not None else None except re.error as e: raise click.BadParameter(f"Not a valid regular expression: {e}") from None @click.command( context_settings={"help_option_names": ["-h", "--help"]}, # While Click does set this field automatically using the docstring, mypyc # (annoyingly) strips 'em so we need to set it here too. help="The uncompromising code formatter.", ) @click.option("-c", "--code", type=str, help="Format the code passed in as a string.") @click.option( "-l", "--line-length", type=int, default=DEFAULT_LINE_LENGTH, help="How many characters per line to allow.", show_default=True, ) @click.option( "-t", "--target-version", type=click.Choice([v.name.lower() for v in TargetVersion]), callback=target_version_option_callback, multiple=True, help=( "Python versions that should be supported by Black's output. You should" " include all versions that your code supports. By default, Black will infer" " target versions from the project metadata in pyproject.toml. If this does" " not yield conclusive results, Black will use per-file auto-detection." ), ) @click.option( "--pyi", is_flag=True, help=( "Format all input files like typing stubs regardless of file extension. This" " is useful when piping source on standard input." ), ) @click.option( "--ipynb", is_flag=True, help=( "Format all input files like Jupyter Notebooks regardless of file extension." " This is useful when piping source on standard input." ), ) @click.option( "--python-cell-magics", multiple=True, help=( "When processing Jupyter Notebooks, add the given magic to the list" f" of known python-magics ({', '.join(sorted(PYTHON_CELL_MAGICS))})." " Useful for formatting cells with custom python magics." ), default=[], ) @click.option( "-x", "--skip-source-first-line", is_flag=True, help="Skip the first line of the source code.", ) @click.option( "-S", "--skip-string-normalization", is_flag=True, help="Don't normalize string quotes or prefixes.", ) @click.option( "-C", "--skip-magic-trailing-comma", is_flag=True, help="Don't use trailing commas as a reason to split lines.", ) @click.option( "--preview", is_flag=True, help=( "Enable potentially disruptive style changes that may be added to Black's main" " functionality in the next major release." ), ) @click.option( "--unstable", is_flag=True, help=( "Enable potentially disruptive style changes that have known bugs or are not" " currently expected to make it into the stable style Black's next major" " release. Implies --preview." ), ) @click.option( "--enable-unstable-feature", type=click.Choice([v.name for v in Preview]), callback=enable_unstable_feature_callback, multiple=True, help=( "Enable specific features included in the `--unstable` style. Requires" " `--preview`. No compatibility guarantees are provided on the behavior" " or existence of any unstable features." ), ) @click.option( "--check", is_flag=True, help=( "Don't write the files back, just return the status. Return code 0 means" " nothing would change. Return code 1 means some files would be reformatted." " Return code 123 means there was an internal error." ), ) @click.option( "--diff", is_flag=True, help=( "Don't write the files back, just output a diff to indicate what changes" " Black would've made. They are printed to stdout so capturing them is simple." ), ) @click.option( "--color/--no-color", is_flag=True, help="Show (or do not show) colored diff. Only applies when --diff is given.", ) @click.option( "--line-ranges", multiple=True, metavar="START-END", help=( "When specified, Black will try its best to only format these lines. This" " option can be specified multiple times, and a union of the lines will be" " formatted. Each range must be specified as two integers connected by a `-`:" " `<START>-<END>`. The `<START>` and `<END>` integer indices are 1-based and" " inclusive on both ends." ), default=(), ) @click.option( "--fast/--safe", is_flag=True, help=( "By default, Black performs an AST safety check after formatting your code." " The --fast flag turns off this check and the --safe flag explicitly enables" " it. [default: --safe]" ), ) @click.option( "--required-version", type=str, help=( "Require a specific version of Black to be running. This is useful for" " ensuring that all contributors to your project are using the same" " version, because different versions of Black may format code a little" " differently. This option can be set in a configuration file for consistent" " results across environments." ), ) @click.option( "--exclude", type=str, callback=validate_regex, help=( "A regular expression that matches files and directories that should be" " excluded on recursive searches. An empty value means no paths are excluded." " Use forward slashes for directories on all platforms (Windows, too)." " By default, Black also ignores all paths listed in .gitignore. Changing this" f" value will override all default exclusions. [default: {DEFAULT_EXCLUDES}]" ), show_default=False, ) @click.option( "--extend-exclude", type=str, callback=validate_regex, help=( "Like --exclude, but adds additional files and directories on top of the" " default values instead of overriding them." ), ) @click.option( "--force-exclude", type=str, callback=validate_regex, help=( "Like --exclude, but files and directories matching this regex will be excluded" " even when they are passed explicitly as arguments. This is useful when" " invoking Black programmatically on changed files, such as in a pre-commit" " hook or editor plugin." ), ) @click.option( "--stdin-filename", type=str, is_eager=True, help=( "The name of the file when passing it through stdin. Useful to make sure Black" " will respect the --force-exclude option on some editors that rely on using" " stdin." ), ) @click.option( "--include", type=str, default=DEFAULT_INCLUDES, callback=validate_regex, help=( "A regular expression that matches files and directories that should be" " included on recursive searches. An empty value means all files are included" " regardless of the name. Use forward slashes for directories on all platforms" " (Windows, too). Overrides all exclusions, including from .gitignore and" " command line options." ), show_default=True, ) @click.option( "-W", "--workers", type=click.IntRange(min=1), default=None, help=( "When Black formats multiple files, it may use a process pool to speed up" " formatting. This option controls the number of parallel workers. This can" " also be specified via the BLACK_NUM_WORKERS environment variable. Defaults" " to the number of CPUs in the system." ), ) @click.option( "-q", "--quiet", is_flag=True, help=( "Stop emitting all non-critical output. Error messages will still be emitted" " (which can silenced by 2>/dev/null)." ), ) @click.option( "-v", "--verbose", is_flag=True, help=( "Emit messages about files that were not changed or were ignored due to" " exclusion patterns. If Black is using a configuration file, a message" " detailing which one it is using will be emitted." ), ) @click.version_option( version=__version__, message=( f"%(prog)s, %(version)s (compiled: {'yes' if COMPILED else 'no'})\n" f"Python ({platform.python_implementation()}) {platform.python_version()}" ), ) @click.argument( "src", nargs=-1, type=click.Path( exists=True, file_okay=True, dir_okay=True, readable=True, allow_dash=True ), is_eager=True, metavar="SRC ...", ) @click.option( "--config", type=click.Path( exists=True, file_okay=True, dir_okay=False, readable=True, allow_dash=False, path_type=str, ), is_eager=True, callback=read_pyproject_toml, help="Read configuration options from a configuration file.", ) @click.option( "--no-cache", is_flag=True, help=( "Skip reading and writing the cache, forcing Black to reformat all" " included files." ), ) @click.pass_context def main( ctx: click.Context, code: str | None, line_length: int, target_version: list[TargetVersion], check: bool, diff: bool, line_ranges: Sequence[str], color: bool, fast: bool, pyi: bool, ipynb: bool, python_cell_magics: Sequence[str], skip_source_first_line: bool, skip_string_normalization: bool, skip_magic_trailing_comma: bool, preview: bool, unstable: bool, enable_unstable_feature: list[Preview], quiet: bool, verbose: bool, required_version: str | None, include: Pattern[str], exclude: Pattern[str] | None, extend_exclude: Pattern[str] | None, force_exclude: Pattern[str] | None, stdin_filename: str | None, workers: int | None, src: tuple[str, ...], config: str | None, no_cache: bool, ) -> None: """The uncompromising code formatter.""" ctx.ensure_object(dict) assert sys.version_info >= (3, 10), "Black requires Python 3.10+" if sys.version_info[:3] == (3, 12, 5): out( "Python 3.12.5 has a memory safety issue that can cause Black's " "AST safety checks to fail. " "Please upgrade to Python 3.12.6 or downgrade to Python 3.12.4" ) ctx.exit(1) if src and code is not None: out( main.get_usage(ctx) + "\n\n'SRC' and 'code' cannot be passed simultaneously." ) ctx.exit(1) if not src and code is None: out(main.get_usage(ctx) + "\n\nOne of 'SRC' or 'code' is required.") ctx.exit(1) # It doesn't do anything if --unstable is also passed, so just allow it. if enable_unstable_feature and not (preview or unstable): out( main.get_usage(ctx) + "\n\n'--enable-unstable-feature' requires '--preview'." ) ctx.exit(1) root, method = ( find_project_root(src, stdin_filename) if code is None else (None, None) ) ctx.obj["root"] = root if verbose: if root: out( f"Identified `{root}` as project root containing a {method}.", fg="blue", ) if config: config_source = ctx.get_parameter_source("config") user_level_config = str(find_user_pyproject_toml()) if config == user_level_config: out( "Using configuration from user-level config at " f"'{user_level_config}'.", fg="blue", ) elif config_source in ( ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP, ): out("Using configuration from project root.", fg="blue") else: out(f"Using configuration in '{config}'.", fg="blue") if ctx.default_map: for param, value in ctx.default_map.items(): out(f"{param}: {value}") error_msg = "Oh no! 💥 💔 💥" if ( required_version and required_version != __version__ and required_version != __version__.split(".")[0] ): err( f"{error_msg} The required version `{required_version}` does not match" f" the running version `{__version__}`!" ) ctx.exit(1) if ipynb and pyi: err("Cannot pass both `pyi` and `ipynb` flags!") ctx.exit(1) write_back = WriteBack.from_configuration(check=check, diff=diff, color=color) if target_version: versions = set(target_version) else: # We'll autodetect later. versions = set() mode = Mode( target_versions=versions, line_length=line_length, is_pyi=pyi, is_ipynb=ipynb, skip_source_first_line=skip_source_first_line, string_normalization=not skip_string_normalization, magic_trailing_comma=not skip_magic_trailing_comma, preview=preview, unstable=unstable, python_cell_magics=set(python_cell_magics), enabled_features=set(enable_unstable_feature), ) lines: list[tuple[int, int]] = [] if line_ranges: if ipynb: err("Cannot use --line-ranges with ipynb files.") ctx.exit(1) try: lines = parse_line_ranges(line_ranges) except ValueError as e: err(str(e)) ctx.exit(1) if code is not None: # Run in quiet mode by default with -c; the extra output isn't useful. # You can still pass -v to get verbose output. quiet = True report = Report(check=check, diff=diff, quiet=quiet, verbose=verbose) if code is not None: reformat_code( content=code, fast=fast, write_back=write_back, mode=mode, report=report, lines=lines, ) else: assert root is not None # root is only None if code is not None try: sources = get_sources( root=root, src=src, quiet=quiet, verbose=verbose, include=include, exclude=exclude, extend_exclude=extend_exclude, force_exclude=force_exclude, report=report, stdin_filename=stdin_filename, ) except GitWildMatchPatternError: ctx.exit(1) if not sources: if verbose or not quiet: out("No Python files are present to be formatted. Nothing to do 😴") if "-" in src: sys.stdout.write(sys.stdin.read()) ctx.exit(0) if len(sources) == 1: reformat_one( src=sources.pop(), fast=fast, write_back=write_back, mode=mode, report=report, lines=lines, no_cache=no_cache, ) else: from black.concurrency import reformat_many if lines: err("Cannot use --line-ranges to format multiple files.") ctx.exit(1) reformat_many( sources=sources, fast=fast, write_back=write_back, mode=mode, report=report, workers=workers, no_cache=no_cache, ) if verbose or not quiet: if code is None and (verbose or report.change_count or report.failure_count): out() out(error_msg if report.return_code else "All done! ✨ 🍰 ✨") if code is None: click.echo(str(report), err=True) ctx.exit(report.return_code) def get_sources( *, root: Path, src: tuple[str, ...], quiet: bool, verbose: bool, include: Pattern[str], exclude: Pattern[str] | None, extend_exclude: Pattern[str] | None, force_exclude: Pattern[str] | None, report: "Report", stdin_filename: str | None, ) -> set[Path]: """Compute the set of files to be formatted.""" sources: set[Path] = set() assert root.is_absolute(), f"INTERNAL ERROR: `root` must be absolute but is {root}" using_default_exclude = exclude is None exclude = re_compile_maybe_verbose(DEFAULT_EXCLUDES) if exclude is None else exclude gitignore: dict[Path, PathSpec] | None = None root_gitignore = get_gitignore(root) for s in src: if s == "-" and stdin_filename: path = Path(stdin_filename) if path_is_excluded(stdin_filename, force_exclude): report.path_ignored( path, "--stdin-filename matches the --force-exclude regular expression", ) continue is_stdin = True else: path = Path(s) is_stdin = False # Compare the logic here to the logic in `gen_python_files`. if is_stdin or path.is_file(): if resolves_outside_root_or_cannot_stat(path, root, report): if verbose: out(f'Skipping invalid source: "{path}"', fg="red") continue root_relative_path = best_effort_relative_path(path, root).as_posix() root_relative_path = "/" + root_relative_path # Hard-exclude any files that matches the `--force-exclude` regex. if path_is_excluded(root_relative_path, force_exclude): report.path_ignored( path, "matches the --force-exclude regular expression" ) continue if is_stdin: path = Path(f"{STDIN_PLACEHOLDER}{path}") if path.suffix == ".ipynb" and not jupyter_dependencies_are_installed( warn=verbose or not quiet ): continue if verbose: out(f'Found input source: "{path}"', fg="blue") sources.add(path) elif path.is_dir(): path = root / (path.resolve().relative_to(root)) if verbose: out(f'Found input source directory: "{path}"', fg="blue") if using_default_exclude: gitignore = { root: root_gitignore, path: get_gitignore(path), } sources.update( gen_python_files( path.iterdir(), root, include, exclude, extend_exclude, force_exclude, report, gitignore, verbose=verbose, quiet=quiet, ) ) elif s == "-": if verbose: out("Found input source stdin", fg="blue") sources.add(path) else: err(f"invalid path: {s}") return sources def reformat_code( content: str, fast: bool, write_back: WriteBack, mode: Mode, report: Report, *, lines: Collection[tuple[int, int]] = (), ) -> None: """ Reformat and print out `content` without spawning child processes. Similar to `reformat_one`, but for string content. `fast`, `write_back`, and `mode` options are passed to :func:`format_file_in_place` or :func:`format_stdin_to_stdout`. """ path = Path("<string>") try: changed = Changed.NO if format_stdin_to_stdout( content=content, fast=fast, write_back=write_back, mode=mode, lines=lines ): changed = Changed.YES report.done(path, changed) except Exception as exc: if report.verbose: traceback.print_exc() report.failed(path, str(exc)) # diff-shades depends on being to monkeypatch this function to operate. I know it's # not ideal, but this shouldn't cause any issues ... hopefully. ~ichard26 @mypyc_attr(patchable=True) def reformat_one( src: Path, fast: bool, write_back: WriteBack, mode: Mode, report: "Report", *, lines: Collection[tuple[int, int]] = (), no_cache: bool = False, ) -> None: """Reformat a single file under `src` without spawning child processes. `fast`, `write_back`, and `mode` options are passed to :func:`format_file_in_place` or :func:`format_stdin_to_stdout`. """ try: changed = Changed.NO if str(src) == "-": is_stdin = True elif str(src).startswith(STDIN_PLACEHOLDER): is_stdin = True # Use the original name again in case we want to print something # to the user src = Path(str(src)[len(STDIN_PLACEHOLDER) :]) else: is_stdin = False if is_stdin: if src.suffix == ".pyi": mode = replace(mode, is_pyi=True) elif src.suffix == ".ipynb": mode = replace(mode, is_ipynb=True) if format_stdin_to_stdout( fast=fast, write_back=write_back, mode=mode, lines=lines ): changed = Changed.YES else: cache = None if no_cache else Cache.read(mode) if cache is not None and write_back not in ( WriteBack.DIFF, WriteBack.COLOR_DIFF, ): if not cache.is_changed(src): changed = Changed.CACHED if changed is not Changed.CACHED and format_file_in_place( src, fast=fast, write_back=write_back, mode=mode, lines=lines ): changed = Changed.YES if cache is not None and ( (write_back is WriteBack.YES and changed is not Changed.CACHED) or (write_back is WriteBack.CHECK and changed is Changed.NO) ): cache.write([src]) report.done(src, changed) except Exception as exc: if report.verbose: traceback.print_exc() report.failed(src, str(exc)) def format_file_in_place( src: Path, fast: bool, mode: Mode, write_back: WriteBack = WriteBack.NO, lock: Any = None, # multiprocessing.Manager().Lock() is some crazy proxy *, lines: Collection[tuple[int, int]] = (), ) -> bool: """Format file under `src` path. Return True if changed. If `write_back` is DIFF, write a diff to stdout. If it is YES, write reformatted code to the file. `mode` and `fast` options are passed to :func:`format_file_contents`. """ if src.suffix == ".pyi": mode = replace(mode, is_pyi=True) elif src.suffix == ".ipynb": mode = replace(mode, is_ipynb=True) then = datetime.fromtimestamp(src.stat().st_mtime, timezone.utc) header = b"" with open(src, "rb") as buf: if mode.skip_source_first_line: header = buf.readline() src_contents, encoding, newline = decode_bytes(buf.read(), mode) try: dst_contents = format_file_contents( src_contents, fast=fast, mode=mode, lines=lines ) except NothingChanged: return False except JSONDecodeError: raise ValueError( f"File '{src}' cannot be parsed as valid Jupyter notebook." ) from None src_contents = header.decode(encoding) + src_contents dst_contents = header.decode(encoding) + dst_contents if write_back == WriteBack.YES: with open(src, "w", encoding=encoding, newline=newline) as f: f.write(dst_contents) elif write_back in (WriteBack.DIFF, WriteBack.COLOR_DIFF): now = datetime.now(timezone.utc) src_name = f"{src}\t{then}" dst_name = f"{src}\t{now}" if mode.is_ipynb: diff_contents = ipynb_diff(src_contents, dst_contents, src_name, dst_name) else: diff_contents = diff(src_contents, dst_contents, src_name, dst_name) if write_back == WriteBack.COLOR_DIFF: diff_contents = color_diff(diff_contents) with lock or nullcontext(): f = io.TextIOWrapper( sys.stdout.buffer, encoding=encoding, newline=newline, write_through=True, ) f = wrap_stream_for_windows(f) f.write(diff_contents) f.detach() return True def format_stdin_to_stdout( fast: bool, *, content: str | None = None, write_back: WriteBack = WriteBack.NO, mode: Mode, lines: Collection[tuple[int, int]] = (), ) -> bool: """Format file on stdin. Return True if changed. If content is None, it's read from sys.stdin. If `write_back` is YES, write reformatted code back to stdout. If it is DIFF, write a diff to stdout. The `mode` argument is passed to :func:`format_file_contents`. """ then = datetime.now(timezone.utc) if content is None: src, encoding, newline = decode_bytes(sys.stdin.buffer.read(), mode) elif Preview.normalize_cr_newlines in mode: src, encoding, newline = content, "utf-8", "\n" else: src, encoding, newline = content, "utf-8", "" dst = src try: dst = format_file_contents(src, fast=fast, mode=mode, lines=lines) return True except NothingChanged: return False finally: f = io.TextIOWrapper( sys.stdout.buffer, encoding=encoding, newline=newline, write_through=True ) if write_back == WriteBack.YES: # Make sure there's a newline after the content if Preview.normalize_cr_newlines in mode: if dst and dst[-1] != "\n" and dst[-1] != "\r": dst += newline else: if dst and dst[-1] != "\n": dst += "\n" f.write(dst) elif write_back in (WriteBack.DIFF, WriteBack.COLOR_DIFF): now = datetime.now(timezone.utc) src_name = f"STDIN\t{then}" dst_name = f"STDOUT\t{now}"
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
true
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/src/black/_width_table.py
src/black/_width_table.py
# Generated by make_width_table.py # wcwidth 0.2.6 # Unicode 15.0.0 from typing import Final WIDTH_TABLE: Final[list[tuple[int, int, int]]] = [ (0, 0, 0), (1, 31, -1), (127, 159, -1), (768, 879, 0), (1155, 1161, 0), (1425, 1469, 0), (1471, 1471, 0), (1473, 1474, 0), (1476, 1477, 0), (1479, 1479, 0), (1552, 1562, 0), (1611, 1631, 0), (1648, 1648, 0), (1750, 1756, 0), (1759, 1764, 0), (1767, 1768, 0), (1770, 1773, 0), (1809, 1809, 0), (1840, 1866, 0), (1958, 1968, 0), (2027, 2035, 0), (2045, 2045, 0), (2070, 2073, 0), (2075, 2083, 0), (2085, 2087, 0), (2089, 2093, 0), (2137, 2139, 0), (2200, 2207, 0), (2250, 2273, 0), (2275, 2306, 0), (2362, 2362, 0), (2364, 2364, 0), (2369, 2376, 0), (2381, 2381, 0), (2385, 2391, 0), (2402, 2403, 0), (2433, 2433, 0), (2492, 2492, 0), (2497, 2500, 0), (2509, 2509, 0), (2530, 2531, 0), (2558, 2558, 0), (2561, 2562, 0), (2620, 2620, 0), (2625, 2626, 0), (2631, 2632, 0), (2635, 2637, 0), (2641, 2641, 0), (2672, 2673, 0), (2677, 2677, 0), (2689, 2690, 0), (2748, 2748, 0), (2753, 2757, 0), (2759, 2760, 0), (2765, 2765, 0), (2786, 2787, 0), (2810, 2815, 0), (2817, 2817, 0), (2876, 2876, 0), (2879, 2879, 0), (2881, 2884, 0), (2893, 2893, 0), (2901, 2902, 0), (2914, 2915, 0), (2946, 2946, 0), (3008, 3008, 0), (3021, 3021, 0), (3072, 3072, 0), (3076, 3076, 0), (3132, 3132, 0), (3134, 3136, 0), (3142, 3144, 0), (3146, 3149, 0), (3157, 3158, 0), (3170, 3171, 0), (3201, 3201, 0), (3260, 3260, 0), (3263, 3263, 0), (3270, 3270, 0), (3276, 3277, 0), (3298, 3299, 0), (3328, 3329, 0), (3387, 3388, 0), (3393, 3396, 0), (3405, 3405, 0), (3426, 3427, 0), (3457, 3457, 0), (3530, 3530, 0), (3538, 3540, 0), (3542, 3542, 0), (3633, 3633, 0), (3636, 3642, 0), (3655, 3662, 0), (3761, 3761, 0), (3764, 3772, 0), (3784, 3790, 0), (3864, 3865, 0), (3893, 3893, 0), (3895, 3895, 0), (3897, 3897, 0), (3953, 3966, 0), (3968, 3972, 0), (3974, 3975, 0), (3981, 3991, 0), (3993, 4028, 0), (4038, 4038, 0), (4141, 4144, 0), (4146, 4151, 0), (4153, 4154, 0), (4157, 4158, 0), (4184, 4185, 0), (4190, 4192, 0), (4209, 4212, 0), (4226, 4226, 0), (4229, 4230, 0), (4237, 4237, 0), (4253, 4253, 0), (4352, 4447, 2), (4957, 4959, 0), (5906, 5908, 0), (5938, 5939, 0), (5970, 5971, 0), (6002, 6003, 0), (6068, 6069, 0), (6071, 6077, 0), (6086, 6086, 0), (6089, 6099, 0), (6109, 6109, 0), (6155, 6157, 0), (6159, 6159, 0), (6277, 6278, 0), (6313, 6313, 0), (6432, 6434, 0), (6439, 6440, 0), (6450, 6450, 0), (6457, 6459, 0), (6679, 6680, 0), (6683, 6683, 0), (6742, 6742, 0), (6744, 6750, 0), (6752, 6752, 0), (6754, 6754, 0), (6757, 6764, 0), (6771, 6780, 0), (6783, 6783, 0), (6832, 6862, 0), (6912, 6915, 0), (6964, 6964, 0), (6966, 6970, 0), (6972, 6972, 0), (6978, 6978, 0), (7019, 7027, 0), (7040, 7041, 0), (7074, 7077, 0), (7080, 7081, 0), (7083, 7085, 0), (7142, 7142, 0), (7144, 7145, 0), (7149, 7149, 0), (7151, 7153, 0), (7212, 7219, 0), (7222, 7223, 0), (7376, 7378, 0), (7380, 7392, 0), (7394, 7400, 0), (7405, 7405, 0), (7412, 7412, 0), (7416, 7417, 0), (7616, 7679, 0), (8203, 8207, 0), (8232, 8238, 0), (8288, 8291, 0), (8400, 8432, 0), (8986, 8987, 2), (9001, 9002, 2), (9193, 9196, 2), (9200, 9200, 2), (9203, 9203, 2), (9725, 9726, 2), (9748, 9749, 2), (9800, 9811, 2), (9855, 9855, 2), (9875, 9875, 2), (9889, 9889, 2), (9898, 9899, 2), (9917, 9918, 2), (9924, 9925, 2), (9934, 9934, 2), (9940, 9940, 2), (9962, 9962, 2), (9970, 9971, 2), (9973, 9973, 2), (9978, 9978, 2), (9981, 9981, 2), (9989, 9989, 2), (9994, 9995, 2), (10024, 10024, 2), (10060, 10060, 2), (10062, 10062, 2), (10067, 10069, 2), (10071, 10071, 2), (10133, 10135, 2), (10160, 10160, 2), (10175, 10175, 2), (11035, 11036, 2), (11088, 11088, 2), (11093, 11093, 2), (11503, 11505, 0), (11647, 11647, 0), (11744, 11775, 0), (11904, 11929, 2), (11931, 12019, 2), (12032, 12245, 2), (12272, 12283, 2), (12288, 12329, 2), (12330, 12333, 0), (12334, 12350, 2), (12353, 12438, 2), (12441, 12442, 0), (12443, 12543, 2), (12549, 12591, 2), (12593, 12686, 2), (12688, 12771, 2), (12784, 12830, 2), (12832, 12871, 2), (12880, 19903, 2), (19968, 42124, 2), (42128, 42182, 2), (42607, 42610, 0), (42612, 42621, 0), (42654, 42655, 0), (42736, 42737, 0), (43010, 43010, 0), (43014, 43014, 0), (43019, 43019, 0), (43045, 43046, 0), (43052, 43052, 0), (43204, 43205, 0), (43232, 43249, 0), (43263, 43263, 0), (43302, 43309, 0), (43335, 43345, 0), (43360, 43388, 2), (43392, 43394, 0), (43443, 43443, 0), (43446, 43449, 0), (43452, 43453, 0), (43493, 43493, 0), (43561, 43566, 0), (43569, 43570, 0), (43573, 43574, 0), (43587, 43587, 0), (43596, 43596, 0), (43644, 43644, 0), (43696, 43696, 0), (43698, 43700, 0), (43703, 43704, 0), (43710, 43711, 0), (43713, 43713, 0), (43756, 43757, 0), (43766, 43766, 0), (44005, 44005, 0), (44008, 44008, 0), (44013, 44013, 0), (44032, 55203, 2), (63744, 64255, 2), (64286, 64286, 0), (65024, 65039, 0), (65040, 65049, 2), (65056, 65071, 0), (65072, 65106, 2), (65108, 65126, 2), (65128, 65131, 2), (65281, 65376, 2), (65504, 65510, 2), (66045, 66045, 0), (66272, 66272, 0), (66422, 66426, 0), (68097, 68099, 0), (68101, 68102, 0), (68108, 68111, 0), (68152, 68154, 0), (68159, 68159, 0), (68325, 68326, 0), (68900, 68903, 0), (69291, 69292, 0), (69373, 69375, 0), (69446, 69456, 0), (69506, 69509, 0), (69633, 69633, 0), (69688, 69702, 0), (69744, 69744, 0), (69747, 69748, 0), (69759, 69761, 0), (69811, 69814, 0), (69817, 69818, 0), (69826, 69826, 0), (69888, 69890, 0), (69927, 69931, 0), (69933, 69940, 0), (70003, 70003, 0), (70016, 70017, 0), (70070, 70078, 0), (70089, 70092, 0), (70095, 70095, 0), (70191, 70193, 0), (70196, 70196, 0), (70198, 70199, 0), (70206, 70206, 0), (70209, 70209, 0), (70367, 70367, 0), (70371, 70378, 0), (70400, 70401, 0), (70459, 70460, 0), (70464, 70464, 0), (70502, 70508, 0), (70512, 70516, 0), (70712, 70719, 0), (70722, 70724, 0), (70726, 70726, 0), (70750, 70750, 0), (70835, 70840, 0), (70842, 70842, 0), (70847, 70848, 0), (70850, 70851, 0), (71090, 71093, 0), (71100, 71101, 0), (71103, 71104, 0), (71132, 71133, 0), (71219, 71226, 0), (71229, 71229, 0), (71231, 71232, 0), (71339, 71339, 0), (71341, 71341, 0), (71344, 71349, 0), (71351, 71351, 0), (71453, 71455, 0), (71458, 71461, 0), (71463, 71467, 0), (71727, 71735, 0), (71737, 71738, 0), (71995, 71996, 0), (71998, 71998, 0), (72003, 72003, 0), (72148, 72151, 0), (72154, 72155, 0), (72160, 72160, 0), (72193, 72202, 0), (72243, 72248, 0), (72251, 72254, 0), (72263, 72263, 0), (72273, 72278, 0), (72281, 72283, 0), (72330, 72342, 0), (72344, 72345, 0), (72752, 72758, 0), (72760, 72765, 0), (72767, 72767, 0), (72850, 72871, 0), (72874, 72880, 0), (72882, 72883, 0), (72885, 72886, 0), (73009, 73014, 0), (73018, 73018, 0), (73020, 73021, 0), (73023, 73029, 0), (73031, 73031, 0), (73104, 73105, 0), (73109, 73109, 0), (73111, 73111, 0), (73459, 73460, 0), (73472, 73473, 0), (73526, 73530, 0), (73536, 73536, 0), (73538, 73538, 0), (78912, 78912, 0), (78919, 78933, 0), (92912, 92916, 0), (92976, 92982, 0), (94031, 94031, 0), (94095, 94098, 0), (94176, 94179, 2), (94180, 94180, 0), (94192, 94193, 2), (94208, 100343, 2), (100352, 101589, 2), (101632, 101640, 2), (110576, 110579, 2), (110581, 110587, 2), (110589, 110590, 2), (110592, 110882, 2), (110898, 110898, 2), (110928, 110930, 2), (110933, 110933, 2), (110948, 110951, 2), (110960, 111355, 2), (113821, 113822, 0), (118528, 118573, 0), (118576, 118598, 0), (119143, 119145, 0), (119163, 119170, 0), (119173, 119179, 0), (119210, 119213, 0), (119362, 119364, 0), (121344, 121398, 0), (121403, 121452, 0), (121461, 121461, 0), (121476, 121476, 0), (121499, 121503, 0), (121505, 121519, 0), (122880, 122886, 0), (122888, 122904, 0), (122907, 122913, 0), (122915, 122916, 0), (122918, 122922, 0), (123023, 123023, 0), (123184, 123190, 0), (123566, 123566, 0), (123628, 123631, 0), (124140, 124143, 0), (125136, 125142, 0), (125252, 125258, 0), (126980, 126980, 2), (127183, 127183, 2), (127374, 127374, 2), (127377, 127386, 2), (127488, 127490, 2), (127504, 127547, 2), (127552, 127560, 2), (127568, 127569, 2), (127584, 127589, 2), (127744, 127776, 2), (127789, 127797, 2), (127799, 127868, 2), (127870, 127891, 2), (127904, 127946, 2), (127951, 127955, 2), (127968, 127984, 2), (127988, 127988, 2), (127992, 128062, 2), (128064, 128064, 2), (128066, 128252, 2), (128255, 128317, 2), (128331, 128334, 2), (128336, 128359, 2), (128378, 128378, 2), (128405, 128406, 2), (128420, 128420, 2), (128507, 128591, 2), (128640, 128709, 2), (128716, 128716, 2), (128720, 128722, 2), (128725, 128727, 2), (128732, 128735, 2), (128747, 128748, 2), (128756, 128764, 2), (128992, 129003, 2), (129008, 129008, 2), (129292, 129338, 2), (129340, 129349, 2), (129351, 129535, 2), (129648, 129660, 2), (129664, 129672, 2), (129680, 129725, 2), (129727, 129733, 2), (129742, 129755, 2), (129760, 129768, 2), (129776, 129784, 2), (131072, 196605, 2), (196608, 262141, 2), (917760, 917999, 0), ]
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/src/black/cache.py
src/black/cache.py
"""Caching of formatted files with feature-based invalidation.""" import hashlib import os import pickle import sys import tempfile from collections.abc import Iterable from dataclasses import dataclass, field from pathlib import Path from typing import NamedTuple from platformdirs import user_cache_dir from _black_version import version as __version__ from black.mode import Mode from black.output import err if sys.version_info >= (3, 11): from typing import Self else: from typing_extensions import Self class FileData(NamedTuple): st_mtime: float st_size: int hash: str def get_cache_dir() -> Path: """Get the cache directory used by black. Users can customize this directory on all systems using `BLACK_CACHE_DIR` environment variable. By default, the cache directory is the user cache directory under the black application. This result is immediately set to a constant `black.cache.CACHE_DIR` as to avoid repeated calls. """ # NOTE: Function mostly exists as a clean way to test getting the cache directory. default_cache_dir = user_cache_dir("black") cache_dir = Path(os.environ.get("BLACK_CACHE_DIR", default_cache_dir)) cache_dir = cache_dir / __version__ return cache_dir CACHE_DIR = get_cache_dir() def get_cache_file(mode: Mode) -> Path: return CACHE_DIR / f"cache.{mode.get_cache_key()}.pickle" @dataclass class Cache: mode: Mode cache_file: Path file_data: dict[str, FileData] = field(default_factory=dict) @classmethod def read(cls, mode: Mode) -> Self: """Read the cache if it exists and is well-formed. If it is not well-formed, the call to write later should resolve the issue. """ cache_file = get_cache_file(mode) try: exists = cache_file.exists() except OSError as e: # Likely file too long; see #4172 and #4174 err(f"Unable to read cache file {cache_file} due to {e}") return cls(mode, cache_file) if not exists: return cls(mode, cache_file) with cache_file.open("rb") as fobj: try: data: dict[str, tuple[float, int, str]] = pickle.load(fobj) file_data = {k: FileData(*v) for k, v in data.items()} except (pickle.UnpicklingError, ValueError, IndexError): return cls(mode, cache_file) return cls(mode, cache_file, file_data) @staticmethod def hash_digest(path: Path) -> str: """Return hash digest for path.""" data = path.read_bytes() return hashlib.sha256(data).hexdigest() @staticmethod def get_file_data(path: Path) -> FileData: """Return file data for path.""" stat = path.stat() hash = Cache.hash_digest(path) return FileData(stat.st_mtime, stat.st_size, hash) def is_changed(self, source: Path) -> bool: """Check if source has changed compared to cached version.""" res_src = source.resolve() old = self.file_data.get(str(res_src)) if old is None: return True st = res_src.stat() if st.st_size != old.st_size: return True if st.st_mtime != old.st_mtime: new_hash = Cache.hash_digest(res_src) if new_hash != old.hash: return True return False def filtered_cached(self, sources: Iterable[Path]) -> tuple[set[Path], set[Path]]: """Split an iterable of paths in `sources` into two sets. The first contains paths of files that modified on disk or are not in the cache. The other contains paths to non-modified files. """ changed: set[Path] = set() done: set[Path] = set() for src in sources: if self.is_changed(src): changed.add(src) else: done.add(src) return changed, done def write(self, sources: Iterable[Path]) -> None: """Update the cache file data and write a new cache file.""" self.file_data.update( **{str(src.resolve()): Cache.get_file_data(src) for src in sources} ) try: CACHE_DIR.mkdir(parents=True, exist_ok=True) with tempfile.NamedTemporaryFile( dir=str(self.cache_file.parent), delete=False ) as f: # We store raw tuples in the cache because it's faster. data: dict[str, tuple[float, int, str]] = { k: (*v,) for k, v in self.file_data.items() } pickle.dump(data, f, protocol=4) os.replace(f.name, self.cache_file) except OSError: pass
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/src/black/concurrency.py
src/black/concurrency.py
""" Formatting many files at once via multiprocessing. Contains entrypoint and utilities. NOTE: this module is only imported if we need to format several files at once. """ from __future__ import annotations import asyncio import logging import os import signal import sys import traceback from collections.abc import Iterable from concurrent.futures import Executor, ProcessPoolExecutor, ThreadPoolExecutor from multiprocessing import Manager from pathlib import Path from typing import Any from mypy_extensions import mypyc_attr from black import WriteBack, format_file_in_place from black.cache import Cache from black.mode import Mode from black.output import err from black.report import Changed, Report def maybe_install_uvloop() -> None: """If our environment has uvloop installed we use it. This is called only from command-line entry points to avoid interfering with the parent process if Black is used as a library. """ try: import uvloop uvloop.install() except ImportError: pass def cancel(tasks: Iterable[asyncio.Future[Any]]) -> None: """asyncio signal handler that cancels all `tasks` and reports to stderr.""" err("Aborted!") for task in tasks: task.cancel() def shutdown(loop: asyncio.AbstractEventLoop) -> None: """Cancel all pending tasks on `loop`, wait for them, and close the loop.""" try: # This part is borrowed from asyncio/runners.py in Python 3.7b2. to_cancel = [task for task in asyncio.all_tasks(loop) if not task.done()] if not to_cancel: return for task in to_cancel: task.cancel() loop.run_until_complete(asyncio.gather(*to_cancel, return_exceptions=True)) finally: # `concurrent.futures.Future` objects cannot be cancelled once they # are already running. There might be some when the `shutdown()` happened. # Silence their logger's spew about the event loop being closed. cf_logger = logging.getLogger("concurrent.futures") cf_logger.setLevel(logging.CRITICAL) loop.close() # diff-shades depends on being to monkeypatch this function to operate. I know it's # not ideal, but this shouldn't cause any issues ... hopefully. ~ichard26 @mypyc_attr(patchable=True) def reformat_many( sources: set[Path], fast: bool, write_back: WriteBack, mode: Mode, report: Report, workers: int | None, no_cache: bool = False, ) -> None: """Reformat multiple files using a ProcessPoolExecutor.""" maybe_install_uvloop() if workers is None: workers = int(os.environ.get("BLACK_NUM_WORKERS", 0)) workers = workers or os.cpu_count() or 1 if sys.platform == "win32": # Work around https://bugs.python.org/issue26903 workers = min(workers, 60) executor: Executor | None = None if workers > 1: try: executor = ProcessPoolExecutor(max_workers=workers) except (ImportError, NotImplementedError, OSError): # we arrive here if the underlying system does not support multi-processing # like in AWS Lambda or Termux, in which case we gracefully fallback to # a ThreadPoolExecutor with just a single worker (more workers would not do # us any good due to the Global Interpreter Lock) pass if executor is None: executor = ThreadPoolExecutor(max_workers=1) loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) try: loop.run_until_complete( schedule_formatting( sources=sources, fast=fast, write_back=write_back, mode=mode, report=report, loop=loop, executor=executor, no_cache=no_cache, ) ) finally: try: shutdown(loop) finally: asyncio.set_event_loop(None) if executor is not None: executor.shutdown() async def schedule_formatting( sources: set[Path], fast: bool, write_back: WriteBack, mode: Mode, report: Report, loop: asyncio.AbstractEventLoop, executor: Executor, no_cache: bool = False, ) -> None: """Run formatting of `sources` in parallel using the provided `executor`. (Use ProcessPoolExecutors for actual parallelism.) `write_back`, `fast`, and `mode` options are passed to :func:`format_file_in_place`. """ cache = None if no_cache else Cache.read(mode) if cache is not None and write_back not in ( WriteBack.DIFF, WriteBack.COLOR_DIFF, ): sources, cached = cache.filtered_cached(sources) for src in sorted(cached): report.done(src, Changed.CACHED) if not sources: return cancelled = [] sources_to_cache = [] lock = None if write_back in (WriteBack.DIFF, WriteBack.COLOR_DIFF): # For diff output, we need locks to ensure we don't interleave output # from different processes. manager = Manager() lock = manager.Lock() tasks = { asyncio.ensure_future( loop.run_in_executor( executor, format_file_in_place, src, fast, mode, write_back, lock ) ): src for src in sorted(sources) } pending = tasks.keys() try: loop.add_signal_handler(signal.SIGINT, cancel, pending) loop.add_signal_handler(signal.SIGTERM, cancel, pending) except NotImplementedError: # There are no good alternatives for these on Windows. pass while pending: done, _ = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED) for task in done: src = tasks.pop(task) if task.cancelled(): cancelled.append(task) elif exc := task.exception(): if report.verbose: traceback.print_exception(type(exc), exc, exc.__traceback__) report.failed(src, str(exc)) else: changed = Changed.YES if task.result() else Changed.NO # If the file was written back or was successfully checked as # well-formatted, store this information in the cache. if write_back is WriteBack.YES or ( write_back is WriteBack.CHECK and changed is Changed.NO ): sources_to_cache.append(src) report.done(src, changed) if cancelled: await asyncio.gather(*cancelled, return_exceptions=True) if sources_to_cache and not no_cache and cache is not None: cache.write(sources_to_cache)
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/src/black/linegen.py
src/black/linegen.py
""" Generating lines of code. """ import re import sys from collections.abc import Collection, Iterator from dataclasses import replace from enum import Enum, auto from functools import partial, wraps from typing import Union, cast from black.brackets import ( COMMA_PRIORITY, DOT_PRIORITY, STRING_PRIORITY, get_leaves_inside_matching_brackets, max_delimiter_priority_in_atom, ) from black.comments import ( FMT_OFF, FMT_ON, contains_fmt_directive, generate_comments, list_comments, ) from black.lines import ( Line, RHSResult, append_leaves, can_be_split, can_omit_invisible_parens, is_line_short_enough, line_to_string, ) from black.mode import Feature, Mode, Preview from black.nodes import ( ASSIGNMENTS, BRACKETS, CLOSING_BRACKETS, OPENING_BRACKETS, STANDALONE_COMMENT, STATEMENT, WHITESPACE, Visitor, ensure_visible, fstring_tstring_to_string, get_annotation_type, has_sibling_with_type, is_arith_like, is_async_stmt_or_funcdef, is_atom_with_invisible_parens, is_docstring, is_empty_tuple, is_generator, is_lpar_token, is_multiline_string, is_name_token, is_one_sequence_between, is_one_tuple, is_parent_function_or_class, is_part_of_annotation, is_rpar_token, is_stub_body, is_stub_suite, is_tuple, is_tuple_containing_star, is_tuple_containing_walrus, is_type_ignore_comment_string, is_vararg, is_walrus_assignment, is_yield, syms, wrap_in_parentheses, ) from black.numerics import normalize_numeric_literal from black.strings import ( fix_multiline_docstring, get_string_prefix, normalize_string_prefix, normalize_string_quotes, normalize_unicode_escape_sequences, ) from black.trans import ( CannotTransform, StringMerger, StringParenStripper, StringParenWrapper, StringSplitter, Transformer, hug_power_op, ) from blib2to3.pgen2 import token from blib2to3.pytree import Leaf, Node # types LeafID = int LN = Union[Leaf, Node] class CannotSplit(CannotTransform): """A readable split that fits the allotted line length is impossible.""" # This isn't a dataclass because @dataclass + Generic breaks mypyc. # See also https://github.com/mypyc/mypyc/issues/827. class LineGenerator(Visitor[Line]): """Generates reformatted Line objects. Empty lines are not emitted. Note: destroys the tree it's visiting by mutating prefixes of its leaves in ways that will no longer stringify to valid Python code on the tree. """ def __init__(self, mode: Mode, features: Collection[Feature]) -> None: self.mode = mode self.features = features self.current_line: Line self.__post_init__() def line(self, indent: int = 0) -> Iterator[Line]: """Generate a line. If the line is empty, only emit if it makes sense. If the line is too long, split it first and then generate. If any lines were generated, set up a new current_line. """ if not self.current_line: self.current_line.depth += indent return # Line is empty, don't emit. Creating a new one unnecessary. if len(self.current_line.leaves) == 1 and is_async_stmt_or_funcdef( self.current_line.leaves[0] ): # Special case for async def/for/with statements. `visit_async_stmt` # adds an `ASYNC` leaf then visits the child def/for/with statement # nodes. Line yields from those nodes shouldn't treat the former # `ASYNC` leaf as a complete line. return complete_line = self.current_line self.current_line = Line(mode=self.mode, depth=complete_line.depth + indent) yield complete_line def visit_default(self, node: LN) -> Iterator[Line]: """Default `visit_*()` implementation. Recurses to children of `node`.""" if isinstance(node, Leaf): any_open_brackets = self.current_line.bracket_tracker.any_open_brackets() for comment in generate_comments(node, mode=self.mode): if any_open_brackets: # any comment within brackets is subject to splitting self.current_line.append(comment) elif comment.type == token.COMMENT: # regular trailing comment self.current_line.append(comment) yield from self.line() else: # regular standalone comment yield from self.line() self.current_line.append(comment) yield from self.line() if any_open_brackets: node.prefix = "" if node.type not in WHITESPACE: self.current_line.append(node) yield from super().visit_default(node) def visit_test(self, node: Node) -> Iterator[Line]: """Visit an `x if y else z` test""" already_parenthesized = ( node.prev_sibling and node.prev_sibling.type == token.LPAR ) if not already_parenthesized: # Similar to logic in wrap_in_parentheses lpar = Leaf(token.LPAR, "") rpar = Leaf(token.RPAR, "") prefix = node.prefix node.prefix = "" lpar.prefix = prefix node.insert_child(0, lpar) node.append_child(rpar) yield from self.visit_default(node) def visit_INDENT(self, node: Leaf) -> Iterator[Line]: """Increase indentation level, maybe yield a line.""" # In blib2to3 INDENT never holds comments. yield from self.line(+1) yield from self.visit_default(node) def visit_DEDENT(self, node: Leaf) -> Iterator[Line]: """Decrease indentation level, maybe yield a line.""" # The current line might still wait for trailing comments. At DEDENT time # there won't be any (they would be prefixes on the preceding NEWLINE). # Emit the line then. yield from self.line() # While DEDENT has no value, its prefix may contain standalone comments # that belong to the current indentation level. Get 'em. yield from self.visit_default(node) # Finally, emit the dedent. yield from self.line(-1) def visit_stmt( self, node: Node, keywords: set[str], parens: set[str] ) -> Iterator[Line]: """Visit a statement. This implementation is shared for `if`, `while`, `for`, `try`, `except`, `def`, `with`, `class`, `assert`, and assignments. The relevant Python language `keywords` for a given statement will be NAME leaves within it. This methods puts those on a separate line. `parens` holds a set of string leaf values immediately after which invisible parens should be put. """ normalize_invisible_parens( node, parens_after=parens, mode=self.mode, features=self.features ) for child in node.children: if is_name_token(child) and child.value in keywords: yield from self.line() yield from self.visit(child) def visit_typeparams(self, node: Node) -> Iterator[Line]: yield from self.visit_default(node) node.children[0].prefix = "" def visit_typevartuple(self, node: Node) -> Iterator[Line]: yield from self.visit_default(node) node.children[1].prefix = "" def visit_paramspec(self, node: Node) -> Iterator[Line]: yield from self.visit_default(node) node.children[1].prefix = "" def visit_dictsetmaker(self, node: Node) -> Iterator[Line]: if Preview.wrap_long_dict_values_in_parens in self.mode: for i, child in enumerate(node.children): if i == 0: continue if node.children[i - 1].type == token.COLON: if ( child.type == syms.atom and child.children[0].type in OPENING_BRACKETS and not is_walrus_assignment(child) ): maybe_make_parens_invisible_in_atom( child, parent=node, mode=self.mode, features=self.features, remove_brackets_around_comma=False, ) else: wrap_in_parentheses(node, child, visible=False) yield from self.visit_default(node) def visit_funcdef(self, node: Node) -> Iterator[Line]: """Visit function definition.""" yield from self.line() # Remove redundant brackets around return type annotation. is_return_annotation = False for child in node.children: if child.type == token.RARROW: is_return_annotation = True elif is_return_annotation: if child.type == syms.atom and child.children[0].type == token.LPAR: if maybe_make_parens_invisible_in_atom( child, parent=node, mode=self.mode, features=self.features, remove_brackets_around_comma=False, ): wrap_in_parentheses(node, child, visible=False) else: wrap_in_parentheses(node, child, visible=False) is_return_annotation = False for child in node.children: yield from self.visit(child) def visit_match_case(self, node: Node) -> Iterator[Line]: """Visit either a match or case statement.""" normalize_invisible_parens( node, parens_after=set(), mode=self.mode, features=self.features ) yield from self.line() for child in node.children: yield from self.visit(child) def visit_suite(self, node: Node) -> Iterator[Line]: """Visit a suite.""" if is_stub_suite(node): yield from self.visit(node.children[2]) else: yield from self.visit_default(node) def visit_simple_stmt(self, node: Node) -> Iterator[Line]: """Visit a statement without nested statements.""" prev_type: int | None = None for child in node.children: if (prev_type is None or prev_type == token.SEMI) and is_arith_like(child): wrap_in_parentheses(node, child, visible=False) prev_type = child.type if node.parent and node.parent.type in STATEMENT: if is_parent_function_or_class(node) and is_stub_body(node): yield from self.visit_default(node) else: yield from self.line(+1) yield from self.visit_default(node) yield from self.line(-1) else: if node.parent and is_stub_suite(node.parent): node.prefix = "" yield from self.visit_default(node) return yield from self.line() yield from self.visit_default(node) def visit_async_stmt(self, node: Node) -> Iterator[Line]: """Visit `async def`, `async for`, `async with`.""" yield from self.line() children = iter(node.children) for child in children: yield from self.visit(child) if child.type == token.ASYNC or child.type == STANDALONE_COMMENT: # STANDALONE_COMMENT happens when `# fmt: skip` is applied on the async # line. break internal_stmt = next(children) yield from self.visit(internal_stmt) def visit_decorators(self, node: Node) -> Iterator[Line]: """Visit decorators.""" for child in node.children: yield from self.line() yield from self.visit(child) def visit_power(self, node: Node) -> Iterator[Line]: for idx, leaf in enumerate(node.children[:-1]): next_leaf = node.children[idx + 1] if not isinstance(leaf, Leaf): continue value = leaf.value.lower() if ( leaf.type == token.NUMBER and next_leaf.type == syms.trailer # Ensure that we are in an attribute trailer and next_leaf.children[0].type == token.DOT # It shouldn't wrap hexadecimal, binary and octal literals and not value.startswith(("0x", "0b", "0o")) # It shouldn't wrap complex literals and "j" not in value ): wrap_in_parentheses(node, leaf) remove_await_parens(node, mode=self.mode, features=self.features) yield from self.visit_default(node) def visit_SEMI(self, leaf: Leaf) -> Iterator[Line]: """Remove a semicolon and put the other statement on a separate line.""" yield from self.line() def visit_ENDMARKER(self, leaf: Leaf) -> Iterator[Line]: """End of file. Process outstanding comments and end with a newline.""" yield from self.visit_default(leaf) yield from self.line() def visit_STANDALONE_COMMENT(self, leaf: Leaf) -> Iterator[Line]: any_open_brackets = self.current_line.bracket_tracker.any_open_brackets() if not any_open_brackets: yield from self.line() # STANDALONE_COMMENT nodes created by our special handling in # normalize_fmt_off for comment-only blocks have fmt:off as the first # line and fmt:on as the last line (each directive on its own line, # not embedded in other text). These should be appended directly # without calling visit_default, which would process their prefix and # lose indentation. Normal STANDALONE_COMMENT nodes go through # visit_default. value = leaf.value lines = value.splitlines() is_fmt_off_block = ( len(lines) >= 2 and contains_fmt_directive(lines[0], FMT_OFF) and contains_fmt_directive(lines[-1], FMT_ON) ) if is_fmt_off_block: # This is a fmt:off/on block from normalize_fmt_off - we still need # to process any prefix comments (like markdown comments) but append # the fmt block itself directly to preserve its formatting # Only process prefix comments if there actually is a prefix with comments if leaf.prefix and any( line.strip().startswith("#") and not contains_fmt_directive(line.strip()) for line in leaf.prefix.split("\n") ): for comment in generate_comments(leaf, mode=self.mode): yield from self.line() self.current_line.append(comment) yield from self.line() # Clear the prefix since we've processed it as comments above leaf.prefix = "" self.current_line.append(leaf) if not any_open_brackets: yield from self.line() else: # Normal standalone comment - process through visit_default yield from self.visit_default(leaf) def visit_factor(self, node: Node) -> Iterator[Line]: """Force parentheses between a unary op and a binary power: -2 ** 8 -> -(2 ** 8) """ _operator, operand = node.children if ( operand.type == syms.power and len(operand.children) == 3 and operand.children[1].type == token.DOUBLESTAR ): lpar = Leaf(token.LPAR, "(") rpar = Leaf(token.RPAR, ")") index = operand.remove() or 0 node.insert_child(index, Node(syms.atom, [lpar, operand, rpar])) yield from self.visit_default(node) def visit_tname(self, node: Node) -> Iterator[Line]: """ Add potential parentheses around types in function parameter lists to be made into real parentheses in case the type hint is too long to fit on a line Examples: def foo(a: int, b: float = 7): ... -> def foo(a: (int), b: (float) = 7): ... """ if len(node.children) == 3 and maybe_make_parens_invisible_in_atom( node.children[2], parent=node, mode=self.mode, features=self.features ): wrap_in_parentheses(node, node.children[2], visible=False) yield from self.visit_default(node) def visit_STRING(self, leaf: Leaf) -> Iterator[Line]: normalize_unicode_escape_sequences(leaf) if is_docstring(leaf) and not re.search(r"\\\s*\n", leaf.value): # We're ignoring docstrings with backslash newline escapes because changing # indentation of those changes the AST representation of the code. if self.mode.string_normalization: docstring = normalize_string_prefix(leaf.value) # We handle string normalization at the end of this method, but since # what we do right now acts differently depending on quote style (ex. # see padding logic below), there's a possibility for unstable # formatting. To avoid a situation where this function formats a # docstring differently on the second pass, normalize it early. docstring = normalize_string_quotes(docstring) else: docstring = leaf.value prefix = get_string_prefix(docstring) docstring = docstring[len(prefix) :] # Remove the prefix quote_char = docstring[0] # A natural way to remove the outer quotes is to do: # docstring = docstring.strip(quote_char) # but that breaks on """""x""" (which is '""x'). # So we actually need to remove the first character and the next two # characters but only if they are the same as the first. quote_len = 1 if docstring[1] != quote_char else 3 docstring = docstring[quote_len:-quote_len] docstring_started_empty = not docstring indent = " " * 4 * self.current_line.depth if is_multiline_string(leaf): docstring = fix_multiline_docstring(docstring, indent) else: docstring = docstring.strip() has_trailing_backslash = False if docstring: # Add some padding if the docstring starts / ends with a quote mark. if docstring[0] == quote_char: docstring = " " + docstring if docstring[-1] == quote_char: docstring += " " if docstring[-1] == "\\": backslash_count = len(docstring) - len(docstring.rstrip("\\")) if backslash_count % 2: # Odd number of tailing backslashes, add some padding to # avoid escaping the closing string quote. docstring += " " has_trailing_backslash = True elif not docstring_started_empty: docstring = " " # We could enforce triple quotes at this point. quote = quote_char * quote_len # It's invalid to put closing single-character quotes on a new line. if quote_len == 3: # We need to find the length of the last line of the docstring # to find if we can add the closing quotes to the line without # exceeding the maximum line length. # If docstring is one line, we don't put the closing quotes on a # separate line because it looks ugly (#3320). lines = docstring.splitlines() last_line_length = len(lines[-1]) if docstring else 0 # If adding closing quotes would cause the last line to exceed # the maximum line length, and the closing quote is not # prefixed by a newline then put a line break before # the closing quotes if ( len(lines) > 1 and last_line_length + quote_len > self.mode.line_length and len(indent) + quote_len <= self.mode.line_length and not has_trailing_backslash ): if leaf.value[-1 - quote_len] == "\n": leaf.value = prefix + quote + docstring + quote else: leaf.value = prefix + quote + docstring + "\n" + indent + quote else: leaf.value = prefix + quote + docstring + quote else: leaf.value = prefix + quote + docstring + quote if self.mode.string_normalization and leaf.type == token.STRING: leaf.value = normalize_string_prefix(leaf.value) leaf.value = normalize_string_quotes(leaf.value) yield from self.visit_default(leaf) def visit_NUMBER(self, leaf: Leaf) -> Iterator[Line]: normalize_numeric_literal(leaf) yield from self.visit_default(leaf) def visit_atom(self, node: Node) -> Iterator[Line]: """Visit any atom""" if len(node.children) == 3: first = node.children[0] last = node.children[-1] if (first.type == token.LSQB and last.type == token.RSQB) or ( first.type == token.LBRACE and last.type == token.RBRACE ): # Lists or sets of one item maybe_make_parens_invisible_in_atom( node.children[1], parent=node, mode=self.mode, features=self.features, ) yield from self.visit_default(node) def visit_fstring(self, node: Node) -> Iterator[Line]: # currently we don't want to format and split f-strings at all. string_leaf = fstring_tstring_to_string(node) node.replace(string_leaf) if "\\" in string_leaf.value and any( "\\" in str(child) for child in node.children if child.type == syms.fstring_replacement_field ): # string normalization doesn't account for nested quotes, # causing breakages. skip normalization when nested quotes exist yield from self.visit_default(string_leaf) return yield from self.visit_STRING(string_leaf) def visit_tstring(self, node: Node) -> Iterator[Line]: # currently we don't want to format and split t-strings at all. string_leaf = fstring_tstring_to_string(node) node.replace(string_leaf) if "\\" in string_leaf.value and any( "\\" in str(child) for child in node.children if child.type == syms.fstring_replacement_field ): # string normalization doesn't account for nested quotes, # causing breakages. skip normalization when nested quotes exist yield from self.visit_default(string_leaf) return yield from self.visit_STRING(string_leaf) # TODO: Uncomment Implementation to format f-string children # fstring_start = node.children[0] # fstring_end = node.children[-1] # assert isinstance(fstring_start, Leaf) # assert isinstance(fstring_end, Leaf) # quote_char = fstring_end.value[0] # quote_idx = fstring_start.value.index(quote_char) # prefix, quote = ( # fstring_start.value[:quote_idx], # fstring_start.value[quote_idx:] # ) # if not is_docstring(node, self.mode): # prefix = normalize_string_prefix(prefix) # assert quote == fstring_end.value # is_raw_fstring = "r" in prefix or "R" in prefix # middles = [ # leaf # for leaf in node.leaves() # if leaf.type == token.FSTRING_MIDDLE # ] # if self.mode.string_normalization: # middles, quote = normalize_fstring_quotes(quote, middles, is_raw_fstring) # fstring_start.value = prefix + quote # fstring_end.value = quote # yield from self.visit_default(node) def visit_comp_for(self, node: Node) -> Iterator[Line]: if Preview.wrap_comprehension_in in self.mode: normalize_invisible_parens( node, parens_after={"in"}, mode=self.mode, features=self.features ) yield from self.visit_default(node) def visit_old_comp_for(self, node: Node) -> Iterator[Line]: yield from self.visit_comp_for(node) def __post_init__(self) -> None: """You are in a twisty little maze of passages.""" self.current_line = Line(mode=self.mode) v = self.visit_stmt Ø: set[str] = set() self.visit_assert_stmt = partial(v, keywords={"assert"}, parens={"assert", ","}) self.visit_if_stmt = partial( v, keywords={"if", "else", "elif"}, parens={"if", "elif"} ) self.visit_while_stmt = partial(v, keywords={"while", "else"}, parens={"while"}) self.visit_for_stmt = partial(v, keywords={"for", "else"}, parens={"for", "in"}) self.visit_try_stmt = partial( v, keywords={"try", "except", "else", "finally"}, parens=Ø ) self.visit_except_clause = partial(v, keywords={"except"}, parens={"except"}) self.visit_with_stmt = partial(v, keywords={"with"}, parens={"with"}) self.visit_classdef = partial(v, keywords={"class"}, parens=Ø) self.visit_expr_stmt = partial(v, keywords=Ø, parens=ASSIGNMENTS) self.visit_return_stmt = partial(v, keywords={"return"}, parens={"return"}) self.visit_import_from = partial(v, keywords=Ø, parens={"import"}) self.visit_del_stmt = partial(v, keywords=Ø, parens={"del"}) self.visit_async_funcdef = self.visit_async_stmt self.visit_decorated = self.visit_decorators # PEP 634 self.visit_match_stmt = self.visit_match_case self.visit_case_block = self.visit_match_case self.visit_guard = partial(v, keywords=Ø, parens={"if"}) def _hugging_power_ops_line_to_string( line: Line, features: Collection[Feature], mode: Mode, ) -> str | None: try: return line_to_string(next(hug_power_op(line, features, mode))) except CannotTransform: return None def transform_line( line: Line, mode: Mode, features: Collection[Feature] = () ) -> Iterator[Line]: """Transform a `line`, potentially splitting it into many lines. They should fit in the allotted `line_length` but might not be able to. `features` are syntactical features that may be used in the output. """ if line.is_comment: yield line return line_str = line_to_string(line) # We need the line string when power operators are hugging to determine if we should # split the line. Default to line_str, if no power operator are present on the line. line_str_hugging_power_ops = ( _hugging_power_ops_line_to_string(line, features, mode) or line_str ) ll = mode.line_length sn = mode.string_normalization string_merge = StringMerger(ll, sn) string_paren_strip = StringParenStripper(ll, sn) string_split = StringSplitter(ll, sn) string_paren_wrap = StringParenWrapper(ll, sn) transformers: list[Transformer] if ( not line.contains_uncollapsable_type_comments() and not line.should_split_rhs and not line.magic_trailing_comma and ( is_line_short_enough(line, mode=mode, line_str=line_str_hugging_power_ops) or line.contains_unsplittable_type_ignore() ) and not (line.inside_brackets and line.contains_standalone_comments()) and not line.contains_implicit_multiline_string_with_comments() ): # Only apply basic string preprocessing, since lines shouldn't be split here. if Preview.string_processing in mode: transformers = [string_merge, string_paren_strip] else: transformers = [] elif line.is_def and not should_split_funcdef_with_rhs(line, mode): transformers = [left_hand_split] else: def _rhs( self: object, line: Line, features: Collection[Feature], mode: Mode ) -> Iterator[Line]: """Wraps calls to `right_hand_split`. The calls increasingly `omit` right-hand trailers (bracket pairs with content), meaning the trailers get glued together to split on another bracket pair instead. """ for omit in generate_trailers_to_omit(line, mode.line_length): lines = list(right_hand_split(line, mode, features, omit=omit)) # Note: this check is only able to figure out if the first line of the # *current* transformation fits in the line length. This is true only # for simple cases. All others require running more transforms via # `transform_line()`. This check doesn't know if those would succeed. if is_line_short_enough(lines[0], mode=mode): yield from lines return # All splits failed, best effort split with no omits. # This mostly happens to multiline strings that are by definition # reported as not fitting a single line, as well as lines that contain # trailing commas (those have to be exploded). yield from right_hand_split(line, mode, features=features) # HACK: nested functions (like _rhs) compiled by mypyc don't retain their # __name__ attribute which is needed in `run_transformer` further down. # Unfortunately a nested class breaks mypyc too. So a class must be created # via type ... https://github.com/mypyc/mypyc/issues/884 rhs = type("rhs", (), {"__call__": _rhs})() if Preview.string_processing in mode: if line.inside_brackets: transformers = [ string_merge, string_paren_strip, string_split, delimiter_split, standalone_comment_split, string_paren_wrap, rhs, ] else: transformers = [ string_merge, string_paren_strip, string_split, string_paren_wrap, rhs, ] else: if line.inside_brackets: transformers = [delimiter_split, standalone_comment_split, rhs] else: transformers = [rhs] # It's always safe to attempt hugging of power operations and pretty much every line # could match. transformers.append(hug_power_op) for transform in transformers: # We are accumulating lines in `result` because we might want to abort # mission and return the original line in the end, or attempt a different # split altogether. try: result = run_transformer(line, transform, mode, features, line_str=line_str) except CannotTransform: continue else: yield from result break else: yield line def should_split_funcdef_with_rhs(line: Line, mode: Mode) -> bool: """If a funcdef has a magic trailing comma in the return type, then we should first split the line with rhs to respect the comma. """ return_type_leaves: list[Leaf] = [] in_return_type = False for leaf in line.leaves: if leaf.type == token.COLON: in_return_type = False if in_return_type: return_type_leaves.append(leaf) if leaf.type == token.RARROW: in_return_type = True # using `bracket_split_build_line` will mess with whitespace, so we duplicate a # couple lines from it. result = Line(mode=line.mode, depth=line.depth) leaves_to_track = get_leaves_inside_matching_brackets(return_type_leaves) for leaf in return_type_leaves: result.append( leaf, preformatted=True,
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
true
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/src/black/ranges.py
src/black/ranges.py
"""Functions related to Black's formatting by line ranges feature.""" import difflib from collections.abc import Collection, Iterator, Sequence from dataclasses import dataclass from black.nodes import ( LN, STANDALONE_COMMENT, Leaf, Node, Visitor, first_leaf, furthest_ancestor_with_last_leaf, last_leaf, syms, ) from blib2to3.pgen2.token import ASYNC, NEWLINE def parse_line_ranges(line_ranges: Sequence[str]) -> list[tuple[int, int]]: lines: list[tuple[int, int]] = [] for lines_str in line_ranges: parts = lines_str.split("-") if len(parts) != 2: raise ValueError( "Incorrect --line-ranges format, expect 'START-END', found" f" {lines_str!r}" ) try: start = int(parts[0]) end = int(parts[1]) except ValueError: raise ValueError( "Incorrect --line-ranges value, expect integer ranges, found" f" {lines_str!r}" ) from None else: lines.append((start, end)) return lines def is_valid_line_range(lines: tuple[int, int]) -> bool: """Returns whether the line range is valid.""" return not lines or lines[0] <= lines[1] def sanitized_lines( lines: Collection[tuple[int, int]], src_contents: str ) -> Collection[tuple[int, int]]: """Returns the valid line ranges for the given source. This removes ranges that are entirely outside the valid lines. Other ranges are normalized so that the start values are at least 1 and the end values are at most the (1-based) index of the last source line. """ if not src_contents: return [] good_lines = [] src_line_count = src_contents.count("\n") if not src_contents.endswith("\n"): src_line_count += 1 for start, end in lines: if start > src_line_count: continue # line-ranges are 1-based start = max(start, 1) if end < start: continue end = min(end, src_line_count) good_lines.append((start, end)) return good_lines def adjusted_lines( lines: Collection[tuple[int, int]], original_source: str, modified_source: str, ) -> list[tuple[int, int]]: """Returns the adjusted line ranges based on edits from the original code. This computes the new line ranges by diffing original_source and modified_source, and adjust each range based on how the range overlaps with the diffs. Note the diff can contain lines outside of the original line ranges. This can happen when the formatting has to be done in adjacent to maintain consistent local results. For example: 1. def my_func(arg1, arg2, 2. arg3,): 3. pass If it restricts to line 2-2, it can't simply reformat line 2, it also has to reformat line 1: 1. def my_func( 2. arg1, 3. arg2, 4. arg3, 5. ): 6. pass In this case, we will expand the line ranges to also include the whole diff block. Args: lines: a collection of line ranges. original_source: the original source. modified_source: the modified source. """ lines_mappings = _calculate_lines_mappings(original_source, modified_source) new_lines = [] # Keep an index of the current search. Since the lines and lines_mappings are # sorted, this makes the search complexity linear. current_mapping_index = 0 for start, end in sorted(lines): start_mapping_index = _find_lines_mapping_index( start, lines_mappings, current_mapping_index, ) end_mapping_index = _find_lines_mapping_index( end, lines_mappings, start_mapping_index, ) current_mapping_index = start_mapping_index if start_mapping_index >= len(lines_mappings) or end_mapping_index >= len( lines_mappings ): # Protect against invalid inputs. continue start_mapping = lines_mappings[start_mapping_index] end_mapping = lines_mappings[end_mapping_index] if start_mapping.is_changed_block: # When the line falls into a changed block, expands to the whole block. new_start = start_mapping.modified_start else: new_start = ( start - start_mapping.original_start + start_mapping.modified_start ) if end_mapping.is_changed_block: # When the line falls into a changed block, expands to the whole block. new_end = end_mapping.modified_end else: new_end = end - end_mapping.original_start + end_mapping.modified_start new_range = (new_start, new_end) if is_valid_line_range(new_range): new_lines.append(new_range) return new_lines def convert_unchanged_lines(src_node: Node, lines: Collection[tuple[int, int]]) -> None: r"""Converts unchanged lines to STANDALONE_COMMENT. The idea is similar to how `# fmt: on/off` is implemented. It also converts the nodes between those markers as a single `STANDALONE_COMMENT` leaf node with the unformatted code as its value. `STANDALONE_COMMENT` is a "fake" token that will be formatted as-is with its prefix normalized. Here we perform two passes: 1. Visit the top-level statements, and convert them to a single `STANDALONE_COMMENT` when unchanged. This speeds up formatting when some of the top-level statements aren't changed. 2. Convert unchanged "unwrapped lines" to `STANDALONE_COMMENT` nodes line by line. "unwrapped lines" are divided by the `NEWLINE` token. e.g. a multi-line statement is *one* "unwrapped line" that ends with `NEWLINE`, even though this statement itself can span multiple lines, and the tokenizer only sees the last '\n' as the `NEWLINE` token. NOTE: During pass (2), comment prefixes and indentations are ALWAYS normalized even when the lines aren't changed. This is fixable by moving more formatting to pass (1). However, it's hard to get it correct when incorrect indentations are used. So we defer this to future optimizations. """ lines_set: set[int] = set() for start, end in lines: lines_set.update(range(start, end + 1)) visitor = _TopLevelStatementsVisitor(lines_set) _ = list(visitor.visit(src_node)) # Consume all results. _convert_unchanged_line_by_line(src_node, lines_set) def _contains_standalone_comment(node: LN) -> bool: if isinstance(node, Leaf): return node.type == STANDALONE_COMMENT else: for child in node.children: if _contains_standalone_comment(child): return True return False class _TopLevelStatementsVisitor(Visitor[None]): """ A node visitor that converts unchanged top-level statements to STANDALONE_COMMENT. This is used in addition to _convert_unchanged_line_by_line, to speed up formatting when there are unchanged top-level classes/functions/statements. """ def __init__(self, lines_set: set[int]): self._lines_set = lines_set def visit_simple_stmt(self, node: Node) -> Iterator[None]: # This is only called for top-level statements, since `visit_suite` # won't visit its children nodes. yield from [] newline_leaf = last_leaf(node) if not newline_leaf: return assert ( newline_leaf.type == NEWLINE ), f"Unexpectedly found leaf.type={newline_leaf.type}" # We need to find the furthest ancestor with the NEWLINE as the last # leaf, since a `suite` can simply be a `simple_stmt` when it puts # its body on the same line. Example: `if cond: pass`. ancestor = furthest_ancestor_with_last_leaf(newline_leaf) if not _get_line_range(ancestor).intersection(self._lines_set): _convert_node_to_standalone_comment(ancestor) def visit_suite(self, node: Node) -> Iterator[None]: yield from [] # If there is a STANDALONE_COMMENT node, it means parts of the node tree # have fmt on/off/skip markers. Those STANDALONE_COMMENT nodes can't # be simply converted by calling str(node). So we just don't convert # here. if _contains_standalone_comment(node): return # Find the semantic parent of this suite. For `async_stmt` and # `async_funcdef`, the ASYNC token is defined on a separate level by the # grammar. semantic_parent = node.parent if semantic_parent is not None: if ( semantic_parent.prev_sibling is not None and semantic_parent.prev_sibling.type == ASYNC ): semantic_parent = semantic_parent.parent if semantic_parent is not None and not _get_line_range( semantic_parent ).intersection(self._lines_set): _convert_node_to_standalone_comment(semantic_parent) def _convert_unchanged_line_by_line(node: Node, lines_set: set[int]) -> None: """Converts unchanged to STANDALONE_COMMENT line by line.""" for leaf in node.leaves(): if leaf.type != NEWLINE: # We only consider "unwrapped lines", which are divided by the NEWLINE # token. continue if leaf.parent and leaf.parent.type == syms.match_stmt: # The `suite` node is defined as: # match_stmt: "match" subject_expr ':' NEWLINE INDENT case_block+ DEDENT # Here we need to check `subject_expr`. The `case_block+` will be # checked by their own NEWLINEs. nodes_to_ignore: list[LN] = [] prev_sibling = leaf.prev_sibling while prev_sibling: nodes_to_ignore.insert(0, prev_sibling) prev_sibling = prev_sibling.prev_sibling if not _get_line_range(nodes_to_ignore).intersection(lines_set): _convert_nodes_to_standalone_comment(nodes_to_ignore, newline=leaf) elif leaf.parent and leaf.parent.type == syms.suite: # The `suite` node is defined as: # suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT # We will check `simple_stmt` and `stmt+` separately against the lines set parent_sibling = leaf.parent.prev_sibling nodes_to_ignore = [] while parent_sibling and parent_sibling.type != syms.suite: # NOTE: Multiple suite nodes can exist as siblings in e.g. `if_stmt`. nodes_to_ignore.insert(0, parent_sibling) parent_sibling = parent_sibling.prev_sibling # Special case for `async_stmt` and `async_funcdef` where the ASYNC # token is on the grandparent node. grandparent = leaf.parent.parent if ( grandparent is not None and grandparent.prev_sibling is not None and grandparent.prev_sibling.type == ASYNC ): nodes_to_ignore.insert(0, grandparent.prev_sibling) if not _get_line_range(nodes_to_ignore).intersection(lines_set): _convert_nodes_to_standalone_comment(nodes_to_ignore, newline=leaf) else: ancestor = furthest_ancestor_with_last_leaf(leaf) # Consider multiple decorators as a whole block, as their # newlines have different behaviors than the rest of the grammar. if ( ancestor.type == syms.decorator and ancestor.parent and ancestor.parent.type == syms.decorators ): ancestor = ancestor.parent if not _get_line_range(ancestor).intersection(lines_set): _convert_node_to_standalone_comment(ancestor) def _convert_node_to_standalone_comment(node: LN) -> None: """Convert node to STANDALONE_COMMENT by modifying the tree inline.""" parent = node.parent if not parent: return first = first_leaf(node) last = last_leaf(node) if not first or not last: return if first is last: # This can happen on the following edge cases: # 1. A block of `# fmt: off/on` code except the `# fmt: on` is placed # on the end of the last line instead of on a new line. # 2. A single backslash on its own line followed by a comment line. # Ideally we don't want to format them when not requested, but fixing # isn't easy. These cases are also badly formatted code, so it isn't # too bad we reformat them. return # The prefix contains comments and indentation whitespaces. They are # reformatted accordingly to the correct indentation level. # This also means the indentation will be changed on the unchanged lines, and # this is actually required to not break incremental reformatting. prefix = first.prefix first.prefix = "" index = node.remove() if index is not None: # Because of the special handling of multiple decorators, if the decorated # item is a single line then there will be a missing newline between the # decorator and item, so add it back. This doesn't affect any other case # since a decorated item with a newline would hit the earlier suite case # in _convert_unchanged_line_by_line that correctly handles the newlines. if node.type == syms.decorated: # A leaf of type decorated wouldn't make sense, since it should always # have at least the decorator + the decorated item, so if this assert # hits that means there's a problem in the parser. assert isinstance(node, Node) # 1 will always be the correct index since before this function is # called all the decorators are collapsed into a single leaf node.insert_child(1, Leaf(NEWLINE, "\n")) # Remove the '\n', as STANDALONE_COMMENT will have '\n' appended when # generating the formatted code. value = str(node)[:-1] parent.insert_child( index, Leaf( STANDALONE_COMMENT, value, prefix=prefix, fmt_pass_converted_first_leaf=first, ), ) def _convert_nodes_to_standalone_comment(nodes: Sequence[LN], *, newline: Leaf) -> None: """Convert nodes to STANDALONE_COMMENT by modifying the tree inline.""" if not nodes: return parent = nodes[0].parent first = first_leaf(nodes[0]) if not parent or not first: return prefix = first.prefix first.prefix = "" value = "".join(str(node) for node in nodes) # The prefix comment on the NEWLINE leaf is the trailing comment of the statement. if newline.prefix: value += newline.prefix newline.prefix = "" index = nodes[0].remove() for node in nodes[1:]: node.remove() if index is not None: parent.insert_child( index, Leaf( STANDALONE_COMMENT, value, prefix=prefix, fmt_pass_converted_first_leaf=first, ), ) def _leaf_line_end(leaf: Leaf) -> int: """Returns the line number of the leaf node's last line.""" if leaf.type == NEWLINE: return leaf.lineno else: # Leaf nodes like multiline strings can occupy multiple lines. return leaf.lineno + str(leaf).count("\n") def _get_line_range(node_or_nodes: LN | list[LN]) -> set[int]: """Returns the line range of this node or list of nodes.""" if isinstance(node_or_nodes, list): nodes = node_or_nodes if not nodes: return set() first = first_leaf(nodes[0]) last = last_leaf(nodes[-1]) if first and last: line_start = first.lineno line_end = _leaf_line_end(last) return set(range(line_start, line_end + 1)) else: return set() else: node = node_or_nodes if isinstance(node, Leaf): return set(range(node.lineno, _leaf_line_end(node) + 1)) else: first = first_leaf(node) last = last_leaf(node) if first and last: return set(range(first.lineno, _leaf_line_end(last) + 1)) else: return set() @dataclass class _LinesMapping: """1-based lines mapping from original source to modified source. Lines [original_start, original_end] from original source are mapped to [modified_start, modified_end]. The ranges are inclusive on both ends. """ original_start: int original_end: int modified_start: int modified_end: int # Whether this range corresponds to a changed block, or an unchanged block. is_changed_block: bool def _calculate_lines_mappings( original_source: str, modified_source: str, ) -> Sequence[_LinesMapping]: """Returns a sequence of _LinesMapping by diffing the sources. For example, given the following diff: import re - def func(arg1, - arg2, arg3): + def func(arg1, arg2, arg3): pass It returns the following mappings: original -> modified (1, 1) -> (1, 1), is_changed_block=False (the "import re" line) (2, 3) -> (2, 2), is_changed_block=True (the diff) (4, 4) -> (3, 3), is_changed_block=False (the "pass" line) You can think of this visually as if it brings up a side-by-side diff, and tries to map the line ranges from the left side to the right side: (1, 1)->(1, 1) 1. import re 1. import re (2, 3)->(2, 2) 2. def func(arg1, 2. def func(arg1, arg2, arg3): 3. arg2, arg3): (4, 4)->(3, 3) 4. pass 3. pass Args: original_source: the original source. modified_source: the modified source. """ matcher = difflib.SequenceMatcher( None, original_source.splitlines(keepends=True), modified_source.splitlines(keepends=True), ) matching_blocks = matcher.get_matching_blocks() lines_mappings: list[_LinesMapping] = [] # matching_blocks is a sequence of "same block of code ranges", see # https://docs.python.org/3/library/difflib.html#difflib.SequenceMatcher.get_matching_blocks # Each block corresponds to a _LinesMapping with is_changed_block=False, # and the ranges between two blocks corresponds to a _LinesMapping with # is_changed_block=True, # NOTE: matching_blocks is 0-based, but _LinesMapping is 1-based. for i, block in enumerate(matching_blocks): if i == 0: if block.a != 0 or block.b != 0: lines_mappings.append( _LinesMapping( original_start=1, original_end=block.a, modified_start=1, modified_end=block.b, is_changed_block=False, ) ) else: previous_block = matching_blocks[i - 1] lines_mappings.append( _LinesMapping( original_start=previous_block.a + previous_block.size + 1, original_end=block.a, modified_start=previous_block.b + previous_block.size + 1, modified_end=block.b, is_changed_block=True, ) ) if i < len(matching_blocks) - 1: lines_mappings.append( _LinesMapping( original_start=block.a + 1, original_end=block.a + block.size, modified_start=block.b + 1, modified_end=block.b + block.size, is_changed_block=False, ) ) return lines_mappings def _find_lines_mapping_index( original_line: int, lines_mappings: Sequence[_LinesMapping], start_index: int, ) -> int: """Returns the original index of the lines mappings for the original line.""" index = start_index while index < len(lines_mappings): mapping = lines_mappings[index] if mapping.original_start <= original_line <= mapping.original_end: return index index += 1 return index
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/src/black/resources/__init__.py
src/black/resources/__init__.py
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/src/blackd/client.py
src/blackd/client.py
import aiohttp from aiohttp.typedefs import StrOrURL import black _DEFAULT_HEADERS = {"Content-Type": "text/plain; charset=utf-8"} class BlackDClient: def __init__( self, url: StrOrURL = "http://localhost:9090", line_length: int | None = None, skip_source_first_line: bool = False, skip_string_normalization: bool = False, skip_magic_trailing_comma: bool = False, preview: bool = False, fast: bool = False, python_variant: str | None = None, diff: bool = False, headers: dict[str, str] | None = None, ): """ Initialize a BlackDClient object. :param url: The URL of the BlackD server. :param line_length: The maximum line length. Corresponds to the ``--line-length`` CLI option. :param skip_source_first_line: True to skip the first line of the source. Corresponds to the ``--skip-source-first-line`` CLI option. :param skip_string_normalization: True to skip string normalization. Corresponds to the ``--skip-string-normalization`` CLI option. :param skip_magic_trailing_comma: True to skip magic trailing comma. Corresponds to the ``--skip-magic-trailing-comma`` CLI option. :param preview: True to enable experimental preview mode. Corresponds to the ``--preview`` CLI option. :param fast: True to enable fast mode. Corresponds to the ``--fast`` CLI option. :param python_variant: The Python variant to use. Corresponds to the ``--pyi`` CLI option if this is "pyi". Otherwise, corresponds to the ``--target-version`` CLI option. :param diff: True to enable diff mode. Corresponds to the ``--diff`` CLI option. :param headers: A dictionary of additional custom headers to send with the request. """ self.url = url self.headers = _DEFAULT_HEADERS.copy() if line_length is not None: self.headers["X-Line-Length"] = str(line_length) if skip_source_first_line: self.headers["X-Skip-Source-First-Line"] = "yes" if skip_string_normalization: self.headers["X-Skip-String-Normalization"] = "yes" if skip_magic_trailing_comma: self.headers["X-Skip-Magic-Trailing-Comma"] = "yes" if preview: self.headers["X-Preview"] = "yes" if fast: self.headers["X-Fast-Or-Safe"] = "fast" if python_variant is not None: self.headers["X-Python-Variant"] = python_variant if diff: self.headers["X-Diff"] = "yes" if headers is not None: self.headers.update(headers) async def format_code(self, unformatted_code: str) -> str: async with aiohttp.ClientSession() as session: async with session.post( self.url, headers=self.headers, data=unformatted_code.encode("utf-8") ) as response: if response.status == 204: # Input is already well-formatted return unformatted_code elif response.status == 200: # Formatting was needed return await response.text() elif response.status == 400: # Input contains a syntax error error_message = await response.text() raise black.InvalidInput(error_message) elif response.status == 500: # Other kind of error while formatting error_message = await response.text() raise RuntimeError(f"Error while formatting: {error_message}") else: # Unexpected response status code raise RuntimeError( f"Unexpected response status code: {response.status}" )
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/src/blackd/__main__.py
src/blackd/__main__.py
import blackd blackd.patched_main()
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/src/blackd/middlewares.py
src/blackd/middlewares.py
from collections.abc import Awaitable, Callable, Iterable from aiohttp.typedefs import Middleware from aiohttp.web_middlewares import middleware from aiohttp.web_request import Request from aiohttp.web_response import StreamResponse Handler = Callable[[Request], Awaitable[StreamResponse]] def cors(allow_headers: Iterable[str]) -> Middleware: @middleware async def impl(request: Request, handler: Handler) -> StreamResponse: is_options = request.method == "OPTIONS" is_preflight = is_options and "Access-Control-Request-Method" in request.headers if is_preflight: resp = StreamResponse() else: resp = await handler(request) origin = request.headers.get("Origin") if not origin: return resp resp.headers["Access-Control-Allow-Origin"] = "*" resp.headers["Access-Control-Expose-Headers"] = "*" if is_options: resp.headers["Access-Control-Allow-Headers"] = ", ".join(allow_headers) resp.headers["Access-Control-Allow-Methods"] = ", ".join( ("OPTIONS", "POST") ) return resp return impl
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/src/blackd/__init__.py
src/blackd/__init__.py
import asyncio import logging from concurrent.futures import Executor, ProcessPoolExecutor from datetime import datetime, timezone from functools import cache, partial from multiprocessing import freeze_support try: from aiohttp import web from multidict import MultiMapping from .middlewares import cors except ImportError as ie: raise ImportError( f"aiohttp dependency is not installed: {ie}. " + "Please re-install black with the '[d]' extra install " + "to obtain aiohttp_cors: `pip install black[d]`" ) from None import click import black from _black_version import version as __version__ from black.concurrency import maybe_install_uvloop from black.mode import Preview # This is used internally by tests to shut down the server prematurely _stop_signal = asyncio.Event() # Request headers PROTOCOL_VERSION_HEADER = "X-Protocol-Version" LINE_LENGTH_HEADER = "X-Line-Length" PYTHON_VARIANT_HEADER = "X-Python-Variant" SKIP_SOURCE_FIRST_LINE = "X-Skip-Source-First-Line" SKIP_STRING_NORMALIZATION_HEADER = "X-Skip-String-Normalization" SKIP_MAGIC_TRAILING_COMMA = "X-Skip-Magic-Trailing-Comma" PREVIEW = "X-Preview" UNSTABLE = "X-Unstable" ENABLE_UNSTABLE_FEATURE = "X-Enable-Unstable-Feature" FAST_OR_SAFE_HEADER = "X-Fast-Or-Safe" DIFF_HEADER = "X-Diff" BLACK_HEADERS = [ PROTOCOL_VERSION_HEADER, LINE_LENGTH_HEADER, PYTHON_VARIANT_HEADER, SKIP_SOURCE_FIRST_LINE, SKIP_STRING_NORMALIZATION_HEADER, SKIP_MAGIC_TRAILING_COMMA, PREVIEW, UNSTABLE, ENABLE_UNSTABLE_FEATURE, FAST_OR_SAFE_HEADER, DIFF_HEADER, ] # Response headers BLACK_VERSION_HEADER = "X-Black-Version" class HeaderError(Exception): pass class InvalidVariantHeader(Exception): pass @click.command(context_settings={"help_option_names": ["-h", "--help"]}) @click.option( "--bind-host", type=str, help="Address to bind the server to.", default="localhost", show_default=True, ) @click.option( "--bind-port", type=int, help="Port to listen on", default=45484, show_default=True ) @click.version_option(version=black.__version__) def main(bind_host: str, bind_port: int) -> None: logging.basicConfig(level=logging.INFO) app = make_app() ver = black.__version__ black.out(f"blackd version {ver} listening on {bind_host} port {bind_port}") web.run_app(app, host=bind_host, port=bind_port, handle_signals=True, print=None) @cache def executor() -> Executor: return ProcessPoolExecutor() def make_app() -> web.Application: app = web.Application( middlewares=[cors(allow_headers=(*BLACK_HEADERS, "Content-Type"))] ) app.add_routes([web.post("/", partial(handle, executor=executor()))]) return app async def handle(request: web.Request, executor: Executor) -> web.Response: headers = {BLACK_VERSION_HEADER: __version__} try: if request.headers.get(PROTOCOL_VERSION_HEADER, "1") != "1": return web.Response( status=501, text="This server only supports protocol version 1" ) fast = False if request.headers.get(FAST_OR_SAFE_HEADER, "safe") == "fast": fast = True try: mode = parse_mode(request.headers) except HeaderError as e: return web.Response(status=400, text=e.args[0]) req_bytes = await request.content.read() charset = request.charset if request.charset is not None else "utf8" req_str = req_bytes.decode(charset) then = datetime.now(timezone.utc) header = "" if mode.skip_source_first_line: first_newline_position: int = req_str.find("\n") + 1 header = req_str[:first_newline_position] req_str = req_str[first_newline_position:] loop = asyncio.get_event_loop() formatted_str = await loop.run_in_executor( executor, partial(black.format_file_contents, req_str, fast=fast, mode=mode) ) if Preview.normalize_cr_newlines not in mode: # Preserve CRLF line endings nl = req_str.find("\n") if nl > 0 and req_str[nl - 1] == "\r": formatted_str = formatted_str.replace("\n", "\r\n") # If, after swapping line endings, nothing changed, then say so if formatted_str == req_str: raise black.NothingChanged # Put the source first line back req_str = header + req_str formatted_str = header + formatted_str # Only output the diff in the HTTP response only_diff = bool(request.headers.get(DIFF_HEADER, False)) if only_diff: now = datetime.now(timezone.utc) src_name = f"In\t{then}" dst_name = f"Out\t{now}" loop = asyncio.get_event_loop() formatted_str = await loop.run_in_executor( executor, partial(black.diff, req_str, formatted_str, src_name, dst_name), ) return web.Response( content_type=request.content_type, charset=charset, headers=headers, text=formatted_str, ) except black.NothingChanged: return web.Response(status=204, headers=headers) except black.InvalidInput as e: return web.Response(status=400, headers=headers, text=str(e)) except Exception as e: logging.exception("Exception during handling a request") return web.Response(status=500, headers=headers, text=str(e)) def parse_mode(headers: MultiMapping[str]) -> black.Mode: try: line_length = int(headers.get(LINE_LENGTH_HEADER, black.DEFAULT_LINE_LENGTH)) except ValueError: raise HeaderError("Invalid line length header value") from None if PYTHON_VARIANT_HEADER in headers: value = headers[PYTHON_VARIANT_HEADER] try: pyi, versions = parse_python_variant_header(value) except InvalidVariantHeader as e: raise HeaderError( f"Invalid value for {PYTHON_VARIANT_HEADER}: {e.args[0]}", ) from None else: pyi = False versions = set() skip_string_normalization = bool( headers.get(SKIP_STRING_NORMALIZATION_HEADER, False) ) skip_magic_trailing_comma = bool(headers.get(SKIP_MAGIC_TRAILING_COMMA, False)) skip_source_first_line = bool(headers.get(SKIP_SOURCE_FIRST_LINE, False)) preview = bool(headers.get(PREVIEW, False)) unstable = bool(headers.get(UNSTABLE, False)) enable_features: set[black.Preview] = set() enable_unstable_features = headers.get(ENABLE_UNSTABLE_FEATURE, "").split(",") for piece in enable_unstable_features: piece = piece.strip() if piece: try: enable_features.add(black.Preview[piece]) except KeyError: raise HeaderError( f"Invalid value for {ENABLE_UNSTABLE_FEATURE}: {piece}", ) from None return black.FileMode( target_versions=versions, is_pyi=pyi, line_length=line_length, skip_source_first_line=skip_source_first_line, string_normalization=not skip_string_normalization, magic_trailing_comma=not skip_magic_trailing_comma, preview=preview, unstable=unstable, enabled_features=enable_features, ) def parse_python_variant_header(value: str) -> tuple[bool, set[black.TargetVersion]]: if value == "pyi": return True, set() else: versions = set() for version in value.split(","): if version.startswith("py"): version = version[len("py") :] if "." in version: major_str, *rest = version.split(".") else: major_str = version[0] rest = [version[1:]] if len(version) > 1 else [] try: major = int(major_str) if major not in (2, 3): raise InvalidVariantHeader("major version must be 2 or 3") if len(rest) > 0: minor = int(rest[0]) if major == 2: raise InvalidVariantHeader("Python 2 is not supported") else: # Default to lowest supported minor version. minor = 7 if major == 2 else 3 version_str = f"PY{major}{minor}" if major == 3 and not hasattr(black.TargetVersion, version_str): raise InvalidVariantHeader(f"3.{minor} is not supported") versions.add(black.TargetVersion[version_str]) except (KeyError, ValueError): raise InvalidVariantHeader("expected e.g. '3.7', 'py3.5'") from None return False, versions def patched_main() -> None: maybe_install_uvloop() freeze_support() main() if __name__ == "__main__": patched_main()
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/test_ipynb.py
tests/test_ipynb.py
import contextlib import pathlib import re from contextlib import AbstractContextManager from contextlib import ExitStack as does_not_raise from dataclasses import replace import pytest from _pytest.monkeypatch import MonkeyPatch from click.testing import CliRunner from black import ( Mode, NothingChanged, format_cell, format_file_contents, format_file_in_place, main, ) from black.handle_ipynb_magics import jupyter_dependencies_are_installed from tests.util import DATA_DIR, get_case_path, read_jupyter_notebook with contextlib.suppress(ModuleNotFoundError): import IPython pytestmark = pytest.mark.jupyter pytest.importorskip("IPython", reason="IPython is an optional dependency") pytest.importorskip("tokenize_rt", reason="tokenize-rt is an optional dependency") JUPYTER_MODE = Mode(is_ipynb=True) EMPTY_CONFIG = DATA_DIR / "empty_pyproject.toml" runner = CliRunner() def test_noop() -> None: src = 'foo = "a"' with pytest.raises(NothingChanged): format_cell(src, fast=True, mode=JUPYTER_MODE) @pytest.mark.parametrize("fast", [True, False]) def test_trailing_semicolon(fast: bool) -> None: src = 'foo = "a" ;' result = format_cell(src, fast=fast, mode=JUPYTER_MODE) expected = 'foo = "a";' assert result == expected def test_trailing_semicolon_with_comment() -> None: src = 'foo = "a" ; # bar' result = format_cell(src, fast=True, mode=JUPYTER_MODE) expected = 'foo = "a"; # bar' assert result == expected def test_trailing_semicolon_with_comment_on_next_line() -> None: src = "import black;\n\n# this is a comment" with pytest.raises(NothingChanged): format_cell(src, fast=True, mode=JUPYTER_MODE) def test_trailing_semicolon_indented() -> None: src = "with foo:\n plot_bar();" with pytest.raises(NothingChanged): format_cell(src, fast=True, mode=JUPYTER_MODE) def test_trailing_semicolon_noop() -> None: src = 'foo = "a";' with pytest.raises(NothingChanged): format_cell(src, fast=True, mode=JUPYTER_MODE) @pytest.mark.parametrize( "mode", [ pytest.param(JUPYTER_MODE, id="default mode"), pytest.param( replace(JUPYTER_MODE, python_cell_magics={"cust1", "cust2"}), id="custom cell magics mode", ), ], ) def test_cell_magic(mode: Mode) -> None: src = "%%time\nfoo =bar" result = format_cell(src, fast=True, mode=mode) expected = "%%time\nfoo = bar" assert result == expected def test_cell_magic_noop() -> None: src = "%%time\n2 + 2" with pytest.raises(NothingChanged): format_cell(src, fast=True, mode=JUPYTER_MODE) @pytest.mark.parametrize( "mode", [ pytest.param(JUPYTER_MODE, id="default mode"), pytest.param( replace(JUPYTER_MODE, python_cell_magics={"cust1", "cust2"}), id="custom cell magics mode", ), ], ) @pytest.mark.parametrize( "src, expected", ( pytest.param("ls =!ls", "ls = !ls", id="System assignment"), pytest.param("!ls\n'foo'", '!ls\n"foo"', id="System call"), pytest.param("!!ls\n'foo'", '!!ls\n"foo"', id="Other system call"), pytest.param("?str\n'foo'", '?str\n"foo"', id="Help"), pytest.param("??str\n'foo'", '??str\n"foo"', id="Other help"), pytest.param( "%matplotlib inline\n'foo'", '%matplotlib inline\n"foo"', id="Line magic with argument", ), pytest.param("%time\n'foo'", '%time\n"foo"', id="Line magic without argument"), pytest.param( "env = %env var", "env = %env var", id="Assignment to environment variable" ), pytest.param("env = %env", "env = %env", id="Assignment to magic"), ), ) def test_magic(src: str, expected: str, mode: Mode) -> None: result = format_cell(src, fast=True, mode=mode) assert result == expected @pytest.mark.parametrize( "src", ( "%%bash\n2+2", "%%html --isolated\n2+2", "%%writefile e.txt\n meh\n meh", ), ) def test_non_python_magics(src: str) -> None: with pytest.raises(NothingChanged): format_cell(src, fast=True, mode=JUPYTER_MODE) @pytest.mark.skipif( IPython.version_info < (8, 3), reason="Change in how TransformerManager transforms this input", ) def test_set_input() -> None: src = "a = b??" expected = "??b" result = format_cell(src, fast=True, mode=JUPYTER_MODE) assert result == expected def test_input_already_contains_transformed_magic() -> None: src = '%time foo()\nget_ipython().run_cell_magic("time", "", "foo()\\n")' with pytest.raises(NothingChanged): format_cell(src, fast=True, mode=JUPYTER_MODE) def test_magic_noop() -> None: src = "ls = !ls" with pytest.raises(NothingChanged): format_cell(src, fast=True, mode=JUPYTER_MODE) def test_cell_magic_with_magic() -> None: src = "%%timeit -n1\nls =!ls" result = format_cell(src, fast=True, mode=JUPYTER_MODE) expected = "%%timeit -n1\nls = !ls" assert result == expected @pytest.mark.parametrize( "src, expected", ( ("\n\n\n%time \n\n", "%time"), (" \n\t\n%%timeit -n4 \t \nx=2 \n\r\n", "%%timeit -n4\nx = 2"), ( " \t\n\n%%capture \nx=2 \n%config \n\n%env\n\t \n \n\n", "%%capture\nx = 2\n%config\n\n%env", ), ), ) def test_cell_magic_with_empty_lines(src: str, expected: str) -> None: result = format_cell(src, fast=True, mode=JUPYTER_MODE) assert result == expected @pytest.mark.parametrize( "mode, expected_output, expectation", [ pytest.param( JUPYTER_MODE, "%%custom_python_magic -n1 -n2\nx=2", pytest.raises(NothingChanged), id="No change when cell magic not registered", ), pytest.param( replace(JUPYTER_MODE, python_cell_magics={"cust1", "cust2"}), "%%custom_python_magic -n1 -n2\nx=2", pytest.raises(NothingChanged), id="No change when other cell magics registered", ), pytest.param( replace(JUPYTER_MODE, python_cell_magics={"custom_python_magic", "cust1"}), "%%custom_python_magic -n1 -n2\nx = 2", does_not_raise(), id="Correctly change when cell magic registered", ), ], ) def test_cell_magic_with_custom_python_magic( mode: Mode, expected_output: str, expectation: AbstractContextManager[object] ) -> None: with expectation: result = format_cell( "%%custom_python_magic -n1 -n2\nx=2", fast=True, mode=mode, ) assert result == expected_output @pytest.mark.parametrize( "src", ( " %%custom_magic \nx=2", "\n\n%%custom_magic\nx=2", "# comment\n%%custom_magic\nx=2", "\n \n # comment with %%time\n\t\n %%custom_magic # comment \nx=2", ), ) def test_cell_magic_with_custom_python_magic_after_spaces_and_comments_noop( src: str, ) -> None: with pytest.raises(NothingChanged): format_cell(src, fast=True, mode=JUPYTER_MODE) def test_cell_magic_nested() -> None: src = "%%time\n%%time\n2+2" result = format_cell(src, fast=True, mode=JUPYTER_MODE) expected = "%%time\n%%time\n2 + 2" assert result == expected def test_cell_magic_with_magic_noop() -> None: src = "%%t -n1\nls = !ls" with pytest.raises(NothingChanged): format_cell(src, fast=True, mode=JUPYTER_MODE) def test_automagic() -> None: src = "pip install black" with pytest.raises(NothingChanged): format_cell(src, fast=True, mode=JUPYTER_MODE) def test_multiline_magic() -> None: src = "%time 1 + \\\n2" with pytest.raises(NothingChanged): format_cell(src, fast=True, mode=JUPYTER_MODE) def test_multiline_no_magic() -> None: src = "1 + \\\n2" result = format_cell(src, fast=True, mode=JUPYTER_MODE) expected = "1 + 2" assert result == expected def test_cell_magic_with_invalid_body() -> None: src = "%%time\nif True" with pytest.raises(NothingChanged): format_cell(src, fast=True, mode=JUPYTER_MODE) def test_empty_cell() -> None: src = "" with pytest.raises(NothingChanged): format_cell(src, fast=True, mode=JUPYTER_MODE) def test_entire_notebook_empty_metadata() -> None: content = read_jupyter_notebook("jupyter", "notebook_empty_metadata") result = format_file_contents(content, fast=True, mode=JUPYTER_MODE) expected = ( "{\n" ' "cells": [\n' " {\n" ' "cell_type": "code",\n' ' "execution_count": null,\n' ' "metadata": {\n' ' "tags": []\n' " },\n" ' "outputs": [],\n' ' "source": [\n' ' "%%time\\n",\n' ' "\\n",\n' ' "print(\\"foo\\")"\n' " ]\n" " },\n" " {\n" ' "cell_type": "code",\n' ' "execution_count": null,\n' ' "metadata": {},\n' ' "outputs": [],\n' ' "source": []\n' " }\n" " ],\n" ' "metadata": {},\n' ' "nbformat": 4,\n' ' "nbformat_minor": 4\n' "}\n" ) assert result == expected def test_entire_notebook_trailing_newline() -> None: content = read_jupyter_notebook("jupyter", "notebook_trailing_newline") result = format_file_contents(content, fast=True, mode=JUPYTER_MODE) expected = ( "{\n" ' "cells": [\n' " {\n" ' "cell_type": "code",\n' ' "execution_count": null,\n' ' "metadata": {\n' ' "tags": []\n' " },\n" ' "outputs": [],\n' ' "source": [\n' ' "%%time\\n",\n' ' "\\n",\n' ' "print(\\"foo\\")"\n' " ]\n" " },\n" " {\n" ' "cell_type": "code",\n' ' "execution_count": null,\n' ' "metadata": {},\n' ' "outputs": [],\n' ' "source": []\n' " }\n" " ],\n" ' "metadata": {\n' ' "interpreter": {\n' ' "hash": "e758f3098b5b55f4d87fe30bbdc1367f20f246b483f96267ee70e6c40cb185d8"\n' # noqa:B950 " },\n" ' "kernelspec": {\n' ' "display_name": "Python 3.8.10 64-bit (\'black\': venv)",\n' ' "name": "python3"\n' " },\n" ' "language_info": {\n' ' "name": "python",\n' ' "version": ""\n' " }\n" " },\n" ' "nbformat": 4,\n' ' "nbformat_minor": 4\n' "}\n" ) assert result == expected def test_entire_notebook_no_trailing_newline() -> None: content = read_jupyter_notebook("jupyter", "notebook_no_trailing_newline") result = format_file_contents(content, fast=True, mode=JUPYTER_MODE) expected = ( "{\n" ' "cells": [\n' " {\n" ' "cell_type": "code",\n' ' "execution_count": null,\n' ' "metadata": {\n' ' "tags": []\n' " },\n" ' "outputs": [],\n' ' "source": [\n' ' "%%time\\n",\n' ' "\\n",\n' ' "print(\\"foo\\")"\n' " ]\n" " },\n" " {\n" ' "cell_type": "code",\n' ' "execution_count": null,\n' ' "metadata": {},\n' ' "outputs": [],\n' ' "source": []\n' " }\n" " ],\n" ' "metadata": {\n' ' "interpreter": {\n' ' "hash": "e758f3098b5b55f4d87fe30bbdc1367f20f246b483f96267ee70e6c40cb185d8"\n' # noqa: B950 " },\n" ' "kernelspec": {\n' ' "display_name": "Python 3.8.10 64-bit (\'black\': venv)",\n' ' "name": "python3"\n' " },\n" ' "language_info": {\n' ' "name": "python",\n' ' "version": ""\n' " }\n" " },\n" ' "nbformat": 4,\n' ' "nbformat_minor": 4\n' "}" ) assert result == expected def test_entire_notebook_without_changes() -> None: content = read_jupyter_notebook("jupyter", "notebook_without_changes") with pytest.raises(NothingChanged): format_file_contents(content, fast=True, mode=JUPYTER_MODE) def test_non_python_notebook() -> None: content = read_jupyter_notebook("jupyter", "non_python_notebook") with pytest.raises(NothingChanged): format_file_contents(content, fast=True, mode=JUPYTER_MODE) def test_empty_string() -> None: with pytest.raises(NothingChanged): format_file_contents("", fast=True, mode=JUPYTER_MODE) def test_unparseable_notebook() -> None: path = get_case_path("jupyter", "notebook_which_cant_be_parsed.ipynb") msg = rf"File '{re.escape(str(path))}' cannot be parsed as valid Jupyter notebook\." with pytest.raises(ValueError, match=msg): format_file_in_place(path, fast=True, mode=JUPYTER_MODE) def test_ipynb_diff_with_change() -> None: result = runner.invoke( main, [ str(get_case_path("jupyter", "notebook_trailing_newline.ipynb")), "--diff", f"--config={EMPTY_CONFIG}", ], ) expected = "@@ -1,3 +1,3 @@\n %%time\n \n-print('foo')\n+print(\"foo\")\n" assert expected in result.output def test_ipynb_diff_with_no_change() -> None: result = runner.invoke( main, [ str(get_case_path("jupyter", "notebook_without_changes.ipynb")), "--diff", f"--config={EMPTY_CONFIG}", ], ) expected = "1 file would be left unchanged." assert expected in result.output def test_cache_isnt_written_if_no_jupyter_deps_single( monkeypatch: MonkeyPatch, tmp_path: pathlib.Path ) -> None: # Check that the cache isn't written to if Jupyter dependencies aren't installed. jupyter_dependencies_are_installed.cache_clear() nb = get_case_path("jupyter", "notebook_trailing_newline.ipynb") tmp_nb = tmp_path / "notebook.ipynb" tmp_nb.write_bytes(nb.read_bytes()) monkeypatch.setattr("black.jupyter_dependencies_are_installed", lambda warn: False) result = runner.invoke( main, [str(tmp_path / "notebook.ipynb"), f"--config={EMPTY_CONFIG}"] ) assert "No Python files are present to be formatted. Nothing to do" in result.output jupyter_dependencies_are_installed.cache_clear() monkeypatch.setattr("black.jupyter_dependencies_are_installed", lambda warn: True) result = runner.invoke( main, [str(tmp_path / "notebook.ipynb"), f"--config={EMPTY_CONFIG}"] ) assert "reformatted" in result.output def test_cache_isnt_written_if_no_jupyter_deps_dir( monkeypatch: MonkeyPatch, tmp_path: pathlib.Path ) -> None: # Check that the cache isn't written to if Jupyter dependencies aren't installed. jupyter_dependencies_are_installed.cache_clear() nb = get_case_path("jupyter", "notebook_trailing_newline.ipynb") tmp_nb = tmp_path / "notebook.ipynb" tmp_nb.write_bytes(nb.read_bytes()) monkeypatch.setattr( "black.files.jupyter_dependencies_are_installed", lambda warn: False ) result = runner.invoke(main, [str(tmp_path), f"--config={EMPTY_CONFIG}"]) assert "No Python files are present to be formatted. Nothing to do" in result.output jupyter_dependencies_are_installed.cache_clear() monkeypatch.setattr( "black.files.jupyter_dependencies_are_installed", lambda warn: True ) result = runner.invoke(main, [str(tmp_path), f"--config={EMPTY_CONFIG}"]) assert "reformatted" in result.output def test_ipynb_flag(tmp_path: pathlib.Path) -> None: nb = get_case_path("jupyter", "notebook_trailing_newline.ipynb") tmp_nb = tmp_path / "notebook.a_file_extension_which_is_definitely_not_ipynb" tmp_nb.write_bytes(nb.read_bytes()) result = runner.invoke( main, [ str(tmp_nb), "--diff", "--ipynb", f"--config={EMPTY_CONFIG}", ], ) expected = "@@ -1,3 +1,3 @@\n %%time\n \n-print('foo')\n+print(\"foo\")\n" assert expected in result.output def test_ipynb_and_pyi_flags() -> None: nb = get_case_path("jupyter", "notebook_trailing_newline.ipynb") result = runner.invoke( main, [ str(nb), "--pyi", "--ipynb", "--diff", f"--config={EMPTY_CONFIG}", ], ) assert isinstance(result.exception, SystemExit) expected = "Cannot pass both `pyi` and `ipynb` flags!\n" assert result.output == expected def test_unable_to_replace_magics(monkeypatch: MonkeyPatch) -> None: src = '%%time\na = b"foo"' monkeypatch.setattr("secrets.token_hex", lambda _: "foo") with pytest.raises( AssertionError, match="Black was not able to replace IPython magic" ): format_cell(src, fast=True, mode=JUPYTER_MODE)
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/test_format.py
tests/test_format.py
from collections.abc import Iterator from dataclasses import replace from typing import Any from unittest.mock import patch import pytest import black from black.mode import TargetVersion from tests.util import ( all_data_cases, assert_format, dump_to_stderr, read_data, read_data_with_mode, ) @pytest.fixture(autouse=True) def patch_dump_to_file(request: Any) -> Iterator[None]: with patch("black.dump_to_file", dump_to_stderr): yield def check_file(subdir: str, filename: str, *, data: bool = True) -> None: args, source, expected = read_data_with_mode(subdir, filename, data=data) assert_format( source, expected, args.mode, fast=args.fast, minimum_version=args.minimum_version, lines=args.lines, no_preview_line_length_1=args.no_preview_line_length_1, ) if args.minimum_version is not None: major, minor = args.minimum_version target_version = TargetVersion[f"PY{major}{minor}"] mode = replace(args.mode, target_versions={target_version}) assert_format( source, expected, mode, fast=args.fast, minimum_version=args.minimum_version, lines=args.lines, no_preview_line_length_1=args.no_preview_line_length_1, ) @pytest.mark.filterwarnings("ignore:invalid escape sequence.*:DeprecationWarning") @pytest.mark.parametrize("filename", all_data_cases("cases")) def test_simple_format(filename: str) -> None: check_file("cases", filename) @pytest.mark.parametrize("filename", all_data_cases("line_ranges_formatted")) def test_line_ranges_line_by_line(filename: str) -> None: args, source, expected = read_data_with_mode("line_ranges_formatted", filename) assert ( source == expected ), "Test cases in line_ranges_formatted must already be formatted." line_count = len(source.splitlines()) for line in range(1, line_count + 1): assert_format( source, expected, args.mode, fast=args.fast, minimum_version=args.minimum_version, lines=[(line, line)], ) # =============== # # Unusual cases # =============== # def test_empty() -> None: source = expected = "" assert_format(source, expected) def test_patma_invalid() -> None: source, expected = read_data("miscellaneous", "pattern_matching_invalid") mode = black.Mode(target_versions={black.TargetVersion.PY310}) with pytest.raises(black.parsing.InvalidInput) as exc_info: assert_format(source, expected, mode, minimum_version=(3, 10)) exc_info.match( "Cannot parse for target version Python 3.10: 10:11: case a := b:" )
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/test_trans.py
tests/test_trans.py
from black.trans import iter_fexpr_spans def test_fexpr_spans() -> None: def check( string: str, expected_spans: list[tuple[int, int]], expected_slices: list[str] ) -> None: spans = list(iter_fexpr_spans(string)) # Checking slices isn't strictly necessary, but it's easier to verify at # a glance than only spans assert len(spans) == len(expected_slices) for (i, j), slice in zip(spans, expected_slices, strict=True): assert 0 <= i <= j <= len(string) assert string[i:j] == slice assert spans == expected_spans # Most of these test cases omit the leading 'f' and leading / closing quotes # for convenience # Some additional property-based tests can be found in # https://github.com/psf/black/pull/2654#issuecomment-981411748 check("""{var}""", [(0, 5)], ["{var}"]) check("""f'{var}'""", [(2, 7)], ["{var}"]) check("""f'{1 + f() + 2 + "asdf"}'""", [(2, 24)], ["""{1 + f() + 2 + "asdf"}"""]) check("""text {var} text""", [(5, 10)], ["{var}"]) check("""text {{ {var} }} text""", [(8, 13)], ["{var}"]) check("""{a} {b} {c}""", [(0, 3), (4, 7), (8, 11)], ["{a}", "{b}", "{c}"]) check("""f'{a} {b} {c}'""", [(2, 5), (6, 9), (10, 13)], ["{a}", "{b}", "{c}"]) check("""{ {} }""", [(0, 6)], ["{ {} }"]) check("""{ {{}} }""", [(0, 8)], ["{ {{}} }"]) check("""{ {{{}}} }""", [(0, 10)], ["{ {{{}}} }"]) check("""{{ {{{}}} }}""", [(5, 7)], ["{}"]) check("""{{ {{{var}}} }}""", [(5, 10)], ["{var}"]) check("""{f"{0}"}""", [(0, 8)], ["""{f"{0}"}"""]) check("""{"'"}""", [(0, 5)], ["""{"'"}"""]) check("""{"{"}""", [(0, 5)], ["""{"{"}"""]) check("""{"}"}""", [(0, 5)], ["""{"}"}"""]) check("""{"{{"}""", [(0, 6)], ["""{"{{"}"""]) check("""{''' '''}""", [(0, 9)], ["""{''' '''}"""]) check("""{'''{'''}""", [(0, 9)], ["""{'''{'''}"""]) check("""{''' {'{ '''}""", [(0, 13)], ["""{''' {'{ '''}"""]) check( '''f\'\'\'-{f"""*{f"+{f'.{x}.'}+"}*"""}-'y\\'\'\'\'''', [(5, 33)], ['''{f"""*{f"+{f'.{x}.'}+"}*"""}'''], ) check(r"""{}{""", [(0, 2)], ["{}"]) check("""f"{'{'''''''''}\"""", [(2, 15)], ["{'{'''''''''}"])
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/util.py
tests/util.py
import argparse import functools import os import shlex import sys import unittest from collections.abc import Collection, Iterator from contextlib import contextmanager from dataclasses import dataclass, field, replace from functools import partial from pathlib import Path from typing import Any import black from black.const import DEFAULT_LINE_LENGTH from black.debug import DebugVisitor from black.mode import TargetVersion from black.output import diff, err, out from black.ranges import parse_line_ranges from . import conftest PYTHON_SUFFIX = ".py" ALLOWED_SUFFIXES = (PYTHON_SUFFIX, ".pyi", ".out", ".diff", ".ipynb") THIS_DIR = Path(__file__).parent DATA_DIR = THIS_DIR / "data" PROJECT_ROOT = THIS_DIR.parent EMPTY_LINE = "# EMPTY LINE WITH WHITESPACE" + " (this comment will be removed)" DETERMINISTIC_HEADER = "[Deterministic header]" PY36_VERSIONS = { TargetVersion.PY36, TargetVersion.PY37, TargetVersion.PY38, TargetVersion.PY39, } DEFAULT_MODE = black.Mode() ff = partial(black.format_file_in_place, mode=DEFAULT_MODE, fast=True) fs = partial(black.format_str, mode=DEFAULT_MODE) @dataclass class TestCaseArgs: mode: black.Mode = field(default_factory=black.Mode) fast: bool = False minimum_version: tuple[int, int] | None = None lines: Collection[tuple[int, int]] = () no_preview_line_length_1: bool = False def _assert_format_equal(expected: str, actual: str) -> None: if actual != expected and (conftest.PRINT_FULL_TREE or conftest.PRINT_TREE_DIFF): bdv: DebugVisitor[Any] actual_out: str = "" expected_out: str = "" if conftest.PRINT_FULL_TREE: out("Expected tree:", fg="green") try: exp_node = black.lib2to3_parse(expected) bdv = DebugVisitor(print_output=conftest.PRINT_FULL_TREE) list(bdv.visit(exp_node)) expected_out = "\n".join(bdv.list_output) except Exception as ve: err(str(ve)) if conftest.PRINT_FULL_TREE: out("Actual tree:", fg="red") try: exp_node = black.lib2to3_parse(actual) bdv = DebugVisitor(print_output=conftest.PRINT_FULL_TREE) list(bdv.visit(exp_node)) actual_out = "\n".join(bdv.list_output) except Exception as ve: err(str(ve)) if conftest.PRINT_TREE_DIFF: out("Tree Diff:") out( diff(expected_out, actual_out, "expected tree", "actual tree") or "Trees do not differ" ) if actual != expected: out(diff(expected, actual, "expected", "actual")) assert actual == expected class FormatFailure(Exception): """Used to wrap failures when assert_format() runs in an extra mode.""" def assert_format( source: str, expected: str, mode: black.Mode = DEFAULT_MODE, *, fast: bool = False, minimum_version: tuple[int, int] | None = None, lines: Collection[tuple[int, int]] = (), no_preview_line_length_1: bool = False, ) -> None: """Convenience function to check that Black formats as expected. You can pass @minimum_version if you're passing code with newer syntax to guard safety guards so they don't just crash with a SyntaxError. Please note this is separate from TargetVerson Mode configuration. """ _assert_format_inner( source, expected, mode, fast=fast, minimum_version=minimum_version, lines=lines ) # For both preview and non-preview tests, ensure that Black doesn't crash on # this code, but don't pass "expected" because the precise output may differ. try: if mode.unstable: new_mode = replace(mode, unstable=False, preview=False) else: new_mode = replace(mode, preview=not mode.preview) _assert_format_inner( source, None, new_mode, fast=fast, minimum_version=minimum_version, lines=lines, ) except Exception as e: text = ( "unstable" if mode.unstable else "non-preview" if mode.preview else "preview" ) raise FormatFailure( f"Black crashed formatting this case in {text} mode." ) from e # Similarly, setting line length to 1 is a good way to catch # stability bugs. Some tests are known to be broken in preview mode with line length # of 1 though, and have marked that with a flag --no-preview-line-length-1 preview_modes = [False] if not no_preview_line_length_1: preview_modes.append(True) for preview_mode in preview_modes: try: _assert_format_inner( source, None, replace(mode, preview=preview_mode, line_length=1, unstable=False), fast=fast, minimum_version=minimum_version, lines=lines, ) except Exception as e: text = "preview" if preview_mode else "non-preview" raise FormatFailure( f"Black crashed formatting this case in {text} mode with line-length=1." ) from e def _assert_format_inner( source: str, expected: str | None = None, mode: black.Mode = DEFAULT_MODE, *, fast: bool = False, minimum_version: tuple[int, int] | None = None, lines: Collection[tuple[int, int]] = (), ) -> None: actual = black.format_str(source, mode=mode, lines=lines) if expected is not None: _assert_format_equal(expected, actual) # It's not useful to run safety checks if we're expecting no changes anyway. The # assertion right above will raise if reality does actually make changes. This just # avoids wasted CPU cycles. if not fast and source != actual: # Unfortunately the AST equivalence check relies on the built-in ast module # being able to parse the code being formatted. This doesn't always work out # when checking modern code on older versions. if minimum_version is None or sys.version_info >= minimum_version: black.assert_equivalent(source, actual) black.assert_stable(source, actual, mode=mode, lines=lines) def dump_to_stderr(*output: str) -> str: return "\n" + "\n".join(output) + "\n" class BlackBaseTestCase(unittest.TestCase): def assertFormatEqual(self, expected: str, actual: str) -> None: _assert_format_equal(expected, actual) def get_base_dir(data: bool) -> Path: return DATA_DIR if data else PROJECT_ROOT def all_data_cases(subdir_name: str, data: bool = True) -> list[str]: cases_dir = get_base_dir(data) / subdir_name assert cases_dir.is_dir() return [case_path.stem for case_path in cases_dir.iterdir()] def get_case_path( subdir_name: str, name: str, data: bool = True, suffix: str = PYTHON_SUFFIX ) -> Path: """Get case path from name""" case_path = get_base_dir(data) / subdir_name / name if not name.endswith(ALLOWED_SUFFIXES): case_path = case_path.with_suffix(suffix) assert case_path.is_file(), f"{case_path} is not a file." return case_path def read_data_with_mode( subdir_name: str, name: str, data: bool = True ) -> tuple[TestCaseArgs, str, str]: """read_data_with_mode('test_name') -> Mode(), 'input', 'output'""" return read_data_from_file(get_case_path(subdir_name, name, data)) def read_data(subdir_name: str, name: str, data: bool = True) -> tuple[str, str]: """read_data('test_name') -> 'input', 'output'""" _, input, output = read_data_with_mode(subdir_name, name, data) return input, output def _parse_minimum_version(version: str) -> tuple[int, int]: major, minor = version.split(".") return int(major), int(minor) @functools.lru_cache def get_flags_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser() parser.add_argument( "--target-version", action="store", type=lambda val: (TargetVersion[val.upper()],), default=(), ) parser.add_argument("--line-length", default=DEFAULT_LINE_LENGTH, type=int) parser.add_argument( "--skip-string-normalization", default=False, action="store_true" ) parser.add_argument("--pyi", default=False, action="store_true") parser.add_argument("--ipynb", default=False, action="store_true") parser.add_argument( "--skip-magic-trailing-comma", default=False, action="store_true" ) parser.add_argument("--preview", default=False, action="store_true") parser.add_argument("--unstable", default=False, action="store_true") parser.add_argument("--fast", default=False, action="store_true") parser.add_argument( "--minimum-version", type=_parse_minimum_version, default=None, help=( "Minimum version of Python where this test case is parseable. If this is" " set, the test case will be run twice: once without the specified" " --target-version, and once with --target-version set to exactly the" " specified version. This ensures that Black's autodetection of the target" " version works correctly." ), ) parser.add_argument("--line-ranges", action="append") parser.add_argument( "--no-preview-line-length-1", default=False, action="store_true", help=( "Don't run in preview mode with --line-length=1, as that's known to cause a" " crash" ), ) return parser def parse_mode(flags_line: str) -> TestCaseArgs: parser = get_flags_parser() args = parser.parse_args(shlex.split(flags_line)) mode = black.Mode( target_versions=set(args.target_version), line_length=args.line_length, string_normalization=not args.skip_string_normalization, is_pyi=args.pyi, is_ipynb=args.ipynb, magic_trailing_comma=not args.skip_magic_trailing_comma, preview=args.preview, unstable=args.unstable, ) if args.line_ranges: lines = parse_line_ranges(args.line_ranges) else: lines = [] return TestCaseArgs( mode=mode, fast=args.fast, minimum_version=args.minimum_version, lines=lines, no_preview_line_length_1=args.no_preview_line_length_1, ) def read_data_from_file(file_name: Path) -> tuple[TestCaseArgs, str, str]: with open(file_name, encoding="utf8") as test: lines = test.readlines() _input: list[str] = [] _output: list[str] = [] result = _input mode = TestCaseArgs() for line in lines: if not _input and line.startswith("# flags: "): mode = parse_mode(line[len("# flags: ") :]) if mode.lines: # Retain the `# flags: ` line when using --line-ranges=. This requires # the `# output` section to also include this line, but retaining the # line is important to make the line ranges match what you see in the # test file. result.append(line) continue line = line.replace(EMPTY_LINE, "") if line.rstrip() == "# output": result = _output continue result.append(line) if _input and not _output: # If there's no output marker, treat the entire file as already pre-formatted. _output = _input[:] return mode, "".join(_input).strip() + "\n", "".join(_output).strip() + "\n" def read_jupyter_notebook(subdir_name: str, name: str, data: bool = True) -> str: return read_jupyter_notebook_from_file( get_case_path(subdir_name, name, data, suffix=".ipynb") ) def read_jupyter_notebook_from_file(file_name: Path) -> str: with open(file_name, mode="rb") as fd: content_bytes = fd.read() return content_bytes.decode() @contextmanager def change_directory(path: Path) -> Iterator[None]: """Context manager to temporarily chdir to a different directory.""" previous_dir = os.getcwd() try: os.chdir(path) yield finally: os.chdir(previous_dir)
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/test_tokenize.py
tests/test_tokenize.py
"""Tests for the blib2to3 tokenizer.""" import sys import textwrap from dataclasses import dataclass import black from blib2to3.pgen2 import token, tokenize @dataclass class Token: type: str string: str start: tokenize.Coord end: tokenize.Coord def get_tokens(text: str) -> list[Token]: """Return the tokens produced by the tokenizer.""" return [ Token(token.tok_name[tok_type], string, start, end) for tok_type, string, start, end, _ in tokenize.tokenize(text) ] def assert_tokenizes(text: str, tokens: list[Token]) -> None: """Assert that the tokenizer produces the expected tokens.""" actual_tokens = get_tokens(text) assert actual_tokens == tokens def test_simple() -> None: assert_tokenizes( "1", [Token("NUMBER", "1", (1, 0), (1, 1)), Token("ENDMARKER", "", (2, 0), (2, 0))], ) assert_tokenizes( "'a'", [ Token("STRING", "'a'", (1, 0), (1, 3)), Token("ENDMARKER", "", (2, 0), (2, 0)), ], ) assert_tokenizes( "a", [Token("NAME", "a", (1, 0), (1, 1)), Token("ENDMARKER", "", (2, 0), (2, 0))], ) def test_fstring() -> None: assert_tokenizes( 'f"x"', [ Token("FSTRING_START", 'f"', (1, 0), (1, 2)), Token("FSTRING_MIDDLE", "x", (1, 2), (1, 3)), Token("FSTRING_END", '"', (1, 3), (1, 4)), Token("ENDMARKER", "", (2, 0), (2, 0)), ], ) assert_tokenizes( 'f"{x}"', [ Token("FSTRING_START", 'f"', (1, 0), (1, 2)), Token("OP", "{", (1, 2), (1, 3)), Token("NAME", "x", (1, 3), (1, 4)), Token("OP", "}", (1, 4), (1, 5)), Token("FSTRING_END", '"', (1, 5), (1, 6)), Token("ENDMARKER", "", (2, 0), (2, 0)), ], ) assert_tokenizes( 'f"{x:y}"\n', [ Token(type="FSTRING_START", string='f"', start=(1, 0), end=(1, 2)), Token(type="OP", string="{", start=(1, 2), end=(1, 3)), Token(type="NAME", string="x", start=(1, 3), end=(1, 4)), Token(type="OP", string=":", start=(1, 4), end=(1, 5)), Token(type="FSTRING_MIDDLE", string="y", start=(1, 5), end=(1, 6)), Token(type="OP", string="}", start=(1, 6), end=(1, 7)), Token(type="FSTRING_END", string='"', start=(1, 7), end=(1, 8)), Token(type="NEWLINE", string="\n", start=(1, 8), end=(1, 9)), Token(type="ENDMARKER", string="", start=(2, 0), end=(2, 0)), ], ) assert_tokenizes( 'f"x\\\n{a}"\n', [ Token(type="FSTRING_START", string='f"', start=(1, 0), end=(1, 2)), Token(type="FSTRING_MIDDLE", string="x\\\n", start=(1, 2), end=(2, 0)), Token(type="OP", string="{", start=(2, 0), end=(2, 1)), Token(type="NAME", string="a", start=(2, 1), end=(2, 2)), Token(type="OP", string="}", start=(2, 2), end=(2, 3)), Token(type="FSTRING_END", string='"', start=(2, 3), end=(2, 4)), Token(type="NEWLINE", string="\n", start=(2, 4), end=(2, 5)), Token(type="ENDMARKER", string="", start=(3, 0), end=(3, 0)), ], ) # Run "echo some code | python tests/test_tokenize.py" to generate test cases. if __name__ == "__main__": code = sys.stdin.read() tokens = get_tokens(code) text = f"assert_tokenizes({code!r}, {tokens!r})" text = black.format_str(text, mode=black.Mode()) print(textwrap.indent(text, " "))
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/test_docs.py
tests/test_docs.py
""" Test that the docs are up to date. """ import re from collections.abc import Sequence from itertools import islice from pathlib import Path import pytest from black.mode import UNSTABLE_FEATURES, Preview DOCS_PATH = Path("docs/the_black_code_style/future_style.md") def check_feature_list( lines: Sequence[str], expected_feature_names: set[str], label: str ) -> str | None: start_index = lines.index(f"(labels/{label}-features)=\n") if start_index == -1: return ( f"Could not find the {label} features list in {DOCS_PATH}. Ensure the" " preview-features label is present." ) num_blank_lines_seen = 0 seen_preview_feature_names = set() for line in islice(lines, start_index + 1, None): if not line.strip(): num_blank_lines_seen += 1 if num_blank_lines_seen == 3: break continue if line.startswith("- "): match = re.search(r"^- `([a-z\d_]+)`", line) if match: seen_preview_feature_names.add(match.group(1)) if seen_preview_feature_names - expected_feature_names: extra = ", ".join(sorted(seen_preview_feature_names - expected_feature_names)) return ( f"The following features should not be in the list of {label} features:" f" {extra}. Please remove them from the {label}-features label in" f" {DOCS_PATH}" ) elif expected_feature_names - seen_preview_feature_names: missing = ", ".join(sorted(expected_feature_names - seen_preview_feature_names)) return ( f"The following features are missing from the list of {label} features:" f" {missing}. Please document them under the {label}-features label in" f" {DOCS_PATH}" ) else: return None def test_feature_lists_are_up_to_date() -> None: repo_root = Path(__file__).parent.parent if not (repo_root / "docs").exists(): pytest.skip("docs not found") with (repo_root / DOCS_PATH).open(encoding="utf-8") as f: future_style = f.readlines() preview_error = check_feature_list( future_style, {feature.name for feature in set(Preview) - UNSTABLE_FEATURES}, "preview", ) assert preview_error is None, preview_error unstable_error = check_feature_list( future_style, {feature.name for feature in UNSTABLE_FEATURES}, "unstable" ) assert unstable_error is None, unstable_error
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/optional.py
tests/optional.py
""" Allows configuring optional test markers in config, see pyproject.toml. Run optional tests with `pytest --run-optional=...`. Mark tests to run only if an optional test ISN'T selected by prepending the mark with "no_". You can specify a "no_" prefix straight in config, in which case you can mark tests to run when this tests ISN'T selected by omitting the "no_" prefix. Specifying the name of the default behavior in `--run-optional=` is harmless. Adapted from https://pypi.org/project/pytest-optional-tests/, (c) 2019 Reece Hart """ import itertools import logging import re from functools import lru_cache from typing import TYPE_CHECKING, Any import pytest from pytest import StashKey log = logging.getLogger(__name__) if TYPE_CHECKING: from _pytest.config import Config from _pytest.config.argparsing import Parser from _pytest.mark.structures import MarkDecorator from _pytest.nodes import Node ALL_POSSIBLE_OPTIONAL_MARKERS = StashKey[frozenset[str]]() ENABLED_OPTIONAL_MARKERS = StashKey[frozenset[str]]() def pytest_addoption(parser: "Parser") -> None: group = parser.getgroup("collect") group.addoption( "--run-optional", action="append", dest="run_optional", default=None, help="Optional test markers to run; comma-separated", ) parser.addini("optional-tests", "List of optional tests markers", "linelist") def pytest_configure(config: "Config") -> None: """Optional tests are markers. Use the syntax in https://docs.pytest.org/en/stable/mark.html#registering-marks. """ # Extract the configured optional-tests from pytest's ini config in a # version-agnostic way. Depending on pytest version, the value can be a # string, a list of strings, or a ConfigValue wrapper (with a `.value` attr). raw_ot_ini: Any = config.inicfg.get("optional-tests") ot_ini_lines: list[str] = [] if raw_ot_ini: value = getattr(raw_ot_ini, "value", raw_ot_ini) if isinstance(value, str): ot_ini_lines = value.strip().split("\n") elif isinstance(value, list): # Best-effort coercion to strings; pytest inis are textual. ot_ini_lines = [str(v) for v in value] else: # Fallback: ignore unexpected shapes (non-iterable, etc.). ot_ini_lines = [] ot_markers: set[str] = set() ot_run: set[str] = set() marker_re = re.compile(r"^\s*(?P<no>no_)?(?P<marker>\w+)(:\s*(?P<description>.*))?") # Iterate over configured markers discovered above. for ot in ot_ini_lines: m = marker_re.match(ot) if not m: raise ValueError(f"{ot!r} doesn't match pytest marker syntax") marker = (m.group("no") or "") + m.group("marker") description = m.group("description") config.addinivalue_line("markers", f"{marker}: {description}") config.addinivalue_line( "markers", f"{no(marker)}: run when `{marker}` not passed" ) ot_markers.add(marker) # collect requested optional tests passed_args = config.getoption("run_optional") if passed_args: ot_run.update(itertools.chain.from_iterable(a.split(",") for a in passed_args)) ot_run |= {no(excluded) for excluded in ot_markers - ot_run} ot_markers |= {no(m) for m in ot_markers} log.info("optional tests to run: %s", ot_run) unknown_tests = ot_run - ot_markers if unknown_tests: raise ValueError(f"Unknown optional tests wanted: {unknown_tests!r}") store = config._store store[ALL_POSSIBLE_OPTIONAL_MARKERS] = frozenset(ot_markers) store[ENABLED_OPTIONAL_MARKERS] = frozenset(ot_run) def pytest_collection_modifyitems(config: "Config", items: "list[Node]") -> None: store = config._store all_possible_optional_markers = store[ALL_POSSIBLE_OPTIONAL_MARKERS] enabled_optional_markers = store[ENABLED_OPTIONAL_MARKERS] for item in items: all_markers_on_test = {m.name for m in item.iter_markers()} optional_markers_on_test = all_markers_on_test & all_possible_optional_markers if not optional_markers_on_test or ( optional_markers_on_test & enabled_optional_markers ): continue log.info("skipping non-requested optional: %s", item) item.add_marker(skip_mark(frozenset(optional_markers_on_test))) @lru_cache def skip_mark(tests: frozenset[str]) -> "MarkDecorator": names = ", ".join(sorted(tests)) return pytest.mark.skip(reason=f"Marked with disabled optional tests ({names})") @lru_cache def no(name: str) -> str: if name.startswith("no_"): return name[len("no_") :] return "no_" + name
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/conftest.py
tests/conftest.py
import pytest pytest_plugins = ["tests.optional"] PRINT_FULL_TREE: bool = False PRINT_TREE_DIFF: bool = True def pytest_addoption(parser: pytest.Parser) -> None: parser.addoption( "--print-full-tree", action="store_true", default=False, help="print full syntax trees on failed tests", ) parser.addoption( "--print-tree-diff", action="store_true", default=True, help="print diff of syntax trees on failed tests", ) def pytest_configure(config: pytest.Config) -> None: global PRINT_FULL_TREE global PRINT_TREE_DIFF PRINT_FULL_TREE = config.getoption("--print-full-tree") PRINT_TREE_DIFF = config.getoption("--print-tree-diff")
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/test_black.py
tests/test_black.py
#!/usr/bin/env python3 import asyncio import inspect import io import itertools import logging import multiprocessing import os import re import sys import textwrap import types from collections.abc import Callable, Iterator, Sequence from concurrent.futures import ThreadPoolExecutor from contextlib import contextmanager, redirect_stderr from dataclasses import fields, replace from importlib.metadata import version as imp_version from io import BytesIO from pathlib import Path, WindowsPath from platform import system from tempfile import TemporaryDirectory from typing import Any, TypeVar from unittest.mock import MagicMock, patch import click import pytest from click import unstyle from click.testing import CliRunner from packaging.version import Version from pathspec import PathSpec import black import black.files from black import Feature, TargetVersion from black import re_compile_maybe_verbose as compile_pattern from black.cache import FileData, get_cache_dir, get_cache_file from black.debug import DebugVisitor from black.mode import Mode, Preview from black.output import color_diff, diff from black.parsing import ASTSafetyError from black.report import Report from black.strings import lines_with_leading_tabs_expanded # Import other test classes from tests.util import ( DATA_DIR, DEFAULT_MODE, DETERMINISTIC_HEADER, PROJECT_ROOT, PY36_VERSIONS, THIS_DIR, BlackBaseTestCase, assert_format, change_directory, dump_to_stderr, ff, fs, get_case_path, read_data, read_data_from_file, ) THIS_FILE = Path(__file__) EMPTY_CONFIG = THIS_DIR / "data" / "empty_pyproject.toml" PY36_ARGS = [f"--target-version={version.name.lower()}" for version in PY36_VERSIONS] DEFAULT_EXCLUDE = black.re_compile_maybe_verbose(black.const.DEFAULT_EXCLUDES) DEFAULT_INCLUDE = black.re_compile_maybe_verbose(black.const.DEFAULT_INCLUDES) T = TypeVar("T") R = TypeVar("R") # Match the time output in a diff, but nothing else DIFF_TIME = re.compile(r"\t[\d\-:+\. ]+") @contextmanager def cache_dir(exists: bool = True) -> Iterator[Path]: with TemporaryDirectory() as workspace: cache_dir = Path(workspace) if not exists: cache_dir = cache_dir / "new" with patch("black.cache.CACHE_DIR", cache_dir): yield cache_dir @contextmanager def event_loop() -> Iterator[None]: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) try: yield finally: loop.close() class FakeContext(click.Context): """A fake click Context for when calling functions that need it.""" def __init__(self) -> None: self.default_map: dict[str, Any] = {} self.params: dict[str, Any] = {} self.command: click.Command = black.main # Dummy root, since most of the tests don't care about it self.obj: dict[str, Any] = {"root": PROJECT_ROOT} class FakeParameter(click.Parameter): """A fake click Parameter for when calling functions that need it.""" def __init__(self) -> None: pass class BlackRunner(CliRunner): """Make sure STDOUT and STDERR are kept separate when testing Black via its CLI.""" def __init__(self) -> None: if Version(imp_version("click")) >= Version("8.2.0"): super().__init__() else: super().__init__(mix_stderr=False) # type: ignore def invokeBlack( args: list[str], exit_code: int = 0, ignore_config: bool = True ) -> None: runner = BlackRunner() if ignore_config: args = ["--verbose", "--config", str(THIS_DIR / "empty.toml"), *args] result = runner.invoke(black.main, args, catch_exceptions=False) assert result.stdout_bytes is not None assert result.stderr_bytes is not None msg = ( f"Failed with args: {args}\n" f"stdout: {result.stdout_bytes.decode()!r}\n" f"stderr: {result.stderr_bytes.decode()!r}\n" f"exception: {result.exception}" ) assert result.exit_code == exit_code, msg class BlackTestCase(BlackBaseTestCase): invokeBlack = staticmethod(invokeBlack) def test_empty_ff(self) -> None: expected = "" tmp_file = Path(black.dump_to_file()) try: self.assertFalse(ff(tmp_file, write_back=black.WriteBack.YES)) actual = tmp_file.read_text(encoding="utf-8") finally: os.unlink(tmp_file) self.assertFormatEqual(expected, actual) @patch("black.dump_to_file", dump_to_stderr) def test_one_empty_line(self) -> None: for nl in ["\n", "\r\n"]: source = expected = nl assert_format(source, expected) def test_one_empty_line_ff(self) -> None: for nl in ["\n", "\r\n"]: expected = nl tmp_file = Path(black.dump_to_file(nl)) if system() == "Windows": # Writing files in text mode automatically uses the system newline, # but in this case we don't want this for testing reasons. See: # https://github.com/psf/black/pull/3348 with open(tmp_file, "wb") as f: f.write(nl.encode("utf-8")) try: self.assertFalse(ff(tmp_file, write_back=black.WriteBack.YES)) with open(tmp_file, "rb") as f: actual = f.read().decode("utf-8") finally: os.unlink(tmp_file) self.assertFormatEqual(expected, actual) def test_piping(self) -> None: _, source, expected = read_data_from_file( PROJECT_ROOT / "src/black/__init__.py" ) result = BlackRunner().invoke( black.main, [ "-", "--fast", f"--line-length={black.DEFAULT_LINE_LENGTH}", f"--config={EMPTY_CONFIG}", ], input=BytesIO(source.encode("utf-8")), ) self.assertEqual(result.exit_code, 0) self.assertFormatEqual(expected, result.stdout) if source != result.stdout: black.assert_equivalent(source, result.stdout) black.assert_stable(source, result.stdout, DEFAULT_MODE) def test_piping_diff(self) -> None: diff_header = re.compile( r"(STDIN|STDOUT)\t\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d\.\d\d\d\d\d\d" r"\+\d\d:\d\d" ) source, _ = read_data("cases", "expression.py") expected, _ = read_data("cases", "expression.diff") args = [ "-", "--fast", f"--line-length={black.DEFAULT_LINE_LENGTH}", "--diff", f"--config={EMPTY_CONFIG}", ] result = BlackRunner().invoke( black.main, args, input=BytesIO(source.encode("utf-8")) ) self.assertEqual(result.exit_code, 0) actual = diff_header.sub(DETERMINISTIC_HEADER, result.stdout) actual = actual.rstrip() + "\n" # the diff output has a trailing space self.assertEqual(expected, actual) def test_piping_diff_with_color(self) -> None: source, _ = read_data("cases", "expression.py") args = [ "-", "--fast", f"--line-length={black.DEFAULT_LINE_LENGTH}", "--diff", "--color", f"--config={EMPTY_CONFIG}", ] result = BlackRunner().invoke( black.main, args, input=BytesIO(source.encode("utf-8")) ) actual = result.output # Again, the contents are checked in a different test, so only look for colors. self.assertIn("\033[1m", actual) self.assertIn("\033[36m", actual) self.assertIn("\033[32m", actual) self.assertIn("\033[31m", actual) self.assertIn("\033[0m", actual) def test_pep_572_version_detection(self) -> None: source, _ = read_data("cases", "pep_572") root = black.lib2to3_parse(source) features = black.get_features_used(root) self.assertIn(black.Feature.ASSIGNMENT_EXPRESSIONS, features) versions = black.detect_target_versions(root) self.assertIn(black.TargetVersion.PY38, versions) def test_pep_695_version_detection(self) -> None: for file in ("type_aliases", "type_params"): source, _ = read_data("cases", file) root = black.lib2to3_parse(source) features = black.get_features_used(root) self.assertIn(black.Feature.TYPE_PARAMS, features) versions = black.detect_target_versions(root) self.assertIn(black.TargetVersion.PY312, versions) def test_pep_696_version_detection(self) -> None: source, _ = read_data("cases", "type_param_defaults") samples = [ source, "type X[T=int] = float", "type X[T:int=int]=int", "type X[*Ts=int]=int", "type X[*Ts=*int]=int", "type X[**P=int]=int", ] for sample in samples: root = black.lib2to3_parse(sample) features = black.get_features_used(root) self.assertIn(black.Feature.TYPE_PARAM_DEFAULTS, features) def test_expression_ff(self) -> None: source, expected = read_data("cases", "expression.py") tmp_file = Path(black.dump_to_file(source)) try: self.assertTrue(ff(tmp_file, write_back=black.WriteBack.YES)) actual = tmp_file.read_text(encoding="utf-8") finally: os.unlink(tmp_file) self.assertFormatEqual(expected, actual) with patch("black.dump_to_file", dump_to_stderr): black.assert_equivalent(source, actual) black.assert_stable(source, actual, DEFAULT_MODE) def test_expression_diff(self) -> None: source, _ = read_data("cases", "expression.py") expected, _ = read_data("cases", "expression.diff") tmp_file = Path(black.dump_to_file(source)) diff_header = re.compile( rf"{re.escape(str(tmp_file))}\t\d\d\d\d-\d\d-\d\d " r"\d\d:\d\d:\d\d\.\d\d\d\d\d\d\+\d\d:\d\d" ) try: result = BlackRunner().invoke( black.main, ["--diff", str(tmp_file), f"--config={EMPTY_CONFIG}"] ) self.assertEqual(result.exit_code, 0) finally: os.unlink(tmp_file) actual = result.stdout actual = diff_header.sub(DETERMINISTIC_HEADER, actual) if expected != actual: dump = black.dump_to_file(actual) msg = ( "Expected diff isn't equal to the actual. If you made changes to" " expression.py and this is an anticipated difference, overwrite" f" tests/data/cases/expression.diff with {dump}" ) self.assertEqual(expected, actual, msg) def test_expression_diff_with_color(self) -> None: source, _ = read_data("cases", "expression.py") expected, _ = read_data("cases", "expression.diff") tmp_file = Path(black.dump_to_file(source)) try: result = BlackRunner().invoke( black.main, ["--diff", "--color", str(tmp_file), f"--config={EMPTY_CONFIG}"], ) finally: os.unlink(tmp_file) actual = result.output # We check the contents of the diff in `test_expression_diff`. All # we need to check here is that color codes exist in the result. self.assertIn("\033[1m", actual) self.assertIn("\033[36m", actual) self.assertIn("\033[32m", actual) self.assertIn("\033[31m", actual) self.assertIn("\033[0m", actual) def test_detect_pos_only_arguments(self) -> None: source, _ = read_data("cases", "pep_570") root = black.lib2to3_parse(source) features = black.get_features_used(root) self.assertIn(black.Feature.POS_ONLY_ARGUMENTS, features) versions = black.detect_target_versions(root) self.assertIn(black.TargetVersion.PY38, versions) def test_detect_debug_f_strings(self) -> None: root = black.lib2to3_parse("""f"{x=}" """) features = black.get_features_used(root) self.assertIn(black.Feature.DEBUG_F_STRINGS, features) versions = black.detect_target_versions(root) self.assertIn(black.TargetVersion.PY38, versions) root = black.lib2to3_parse( """f"{x}"\nf'{"="}'\nf'{(x:=5)}'\nf'{f(a="3=")}'\nf'{x:=10}'\n""" ) features = black.get_features_used(root) self.assertNotIn(black.Feature.DEBUG_F_STRINGS, features) root = black.lib2to3_parse( """f"heard a rumour that { f'{1+1=}' } ... seems like it could be true" """ ) features = black.get_features_used(root) self.assertIn(black.Feature.DEBUG_F_STRINGS, features) @patch("black.dump_to_file", dump_to_stderr) def test_string_quotes(self) -> None: source, expected = read_data("miscellaneous", "string_quotes") mode = black.Mode(unstable=True) assert_format(source, expected, mode) mode = replace(mode, string_normalization=False) not_normalized = fs(source, mode=mode) self.assertFormatEqual(source.replace("\\\n", ""), not_normalized) black.assert_equivalent(source, not_normalized) black.assert_stable(source, not_normalized, mode=mode) def test_skip_source_first_line(self) -> None: source, _ = read_data("miscellaneous", "invalid_header") tmp_file = Path(black.dump_to_file(source)) # Full source should fail (invalid syntax at header) self.invokeBlack([str(tmp_file), "--diff", "--check"], exit_code=123) # So, skipping the first line should work result = BlackRunner().invoke( black.main, [str(tmp_file), "-x", f"--config={EMPTY_CONFIG}"] ) self.assertEqual(result.exit_code, 0) actual = tmp_file.read_text(encoding="utf-8") self.assertFormatEqual(source, actual) def test_skip_source_first_line_when_mixing_newlines(self) -> None: code_mixing_newlines = b"Header will be skipped\r\ni = [1,2,3]\nj = [1,2,3]\n" expected = b"Header will be skipped\r\ni = [1, 2, 3]\nj = [1, 2, 3]\n" with TemporaryDirectory() as workspace: test_file = Path(workspace) / "skip_header.py" test_file.write_bytes(code_mixing_newlines) mode = replace(DEFAULT_MODE, skip_source_first_line=True) ff(test_file, mode=mode, write_back=black.WriteBack.YES) self.assertEqual(test_file.read_bytes(), expected) def test_skip_magic_trailing_comma(self) -> None: source, _ = read_data("cases", "expression") expected, _ = read_data( "miscellaneous", "expression_skip_magic_trailing_comma.diff" ) tmp_file = Path(black.dump_to_file(source)) diff_header = re.compile( rf"{re.escape(str(tmp_file))}\t\d\d\d\d-\d\d-\d\d " r"\d\d:\d\d:\d\d\.\d\d\d\d\d\d\+\d\d:\d\d" ) try: result = BlackRunner().invoke( black.main, ["-C", "--diff", str(tmp_file), f"--config={EMPTY_CONFIG}"] ) self.assertEqual(result.exit_code, 0) finally: os.unlink(tmp_file) actual = result.stdout actual = diff_header.sub(DETERMINISTIC_HEADER, actual) actual = actual.rstrip() + "\n" # the diff output has a trailing space if expected != actual: dump = black.dump_to_file(actual) msg = ( "Expected diff isn't equal to the actual. If you made changes to" " expression.py and this is an anticipated difference, overwrite" " tests/data/miscellaneous/expression_skip_magic_trailing_comma.diff" f" with {dump}" ) self.assertEqual(expected, actual, msg) @patch("black.dump_to_file", dump_to_stderr) def test_python37(self) -> None: source_path = get_case_path("cases", "python37") _, source, expected = read_data_from_file(source_path) actual = fs(source) self.assertFormatEqual(expected, actual) black.assert_equivalent(source, actual) black.assert_stable(source, actual, DEFAULT_MODE) # ensure black can parse this when the target is 3.7 self.invokeBlack([str(source_path), "--target-version", "py37"]) def test_tab_comment_indentation(self) -> None: contents_tab = "if 1:\n\tif 2:\n\t\tpass\n\t# comment\n\tpass\n" contents_spc = "if 1:\n if 2:\n pass\n # comment\n pass\n" self.assertFormatEqual(contents_spc, fs(contents_spc)) self.assertFormatEqual(contents_spc, fs(contents_tab)) contents_tab = "if 1:\n\tif 2:\n\t\tpass\n\t\t# comment\n\tpass\n" contents_spc = "if 1:\n if 2:\n pass\n # comment\n pass\n" self.assertFormatEqual(contents_spc, fs(contents_spc)) self.assertFormatEqual(contents_spc, fs(contents_tab)) def test_false_positive_symlink_output_issue_3384(self) -> None: # Emulate the behavior when using the CLI (`black ./child --verbose`), which # involves patching some `pathlib.Path` methods. In particular, `is_dir` is # patched only on its first call: when checking if "./child" is a directory it # should return True. The "./child" folder exists relative to the cwd when # running from CLI, but fails when running the tests because cwd is different project_root = Path(THIS_DIR / "data" / "nested_gitignore_tests") working_directory = project_root / "root" with change_directory(working_directory): # Note that the root folder (project_root) isn't the folder # named "root" (aka working_directory) report = MagicMock(verbose=True) black.get_sources( root=project_root, src=("./child",), quiet=False, verbose=True, include=DEFAULT_INCLUDE, exclude=None, report=report, extend_exclude=None, force_exclude=None, stdin_filename=None, ) assert not any( mock_args[1].startswith("is a symbolic link that points outside") for _, mock_args, _ in report.path_ignored.mock_calls ), "A symbolic link was reported." report.path_ignored.assert_called_once_with( Path(working_directory, "child", "b.py"), "matches a .gitignore file content", ) def test_report_verbose(self) -> None: report = Report(verbose=True) out_lines = [] err_lines = [] def out(msg: str, **kwargs: Any) -> None: out_lines.append(msg) def err(msg: str, **kwargs: Any) -> None: err_lines.append(msg) with patch("black.output._out", out), patch("black.output._err", err): report.done(Path("f1"), black.Changed.NO) self.assertEqual(len(out_lines), 1) self.assertEqual(len(err_lines), 0) self.assertEqual(out_lines[-1], "f1 already well formatted, good job.") self.assertEqual(unstyle(str(report)), "1 file left unchanged.") self.assertEqual(report.return_code, 0) report.done(Path("f2"), black.Changed.YES) self.assertEqual(len(out_lines), 2) self.assertEqual(len(err_lines), 0) self.assertEqual(out_lines[-1], "reformatted f2") self.assertEqual( unstyle(str(report)), "1 file reformatted, 1 file left unchanged." ) report.done(Path("f3"), black.Changed.CACHED) self.assertEqual(len(out_lines), 3) self.assertEqual(len(err_lines), 0) self.assertEqual( out_lines[-1], "f3 wasn't modified on disk since last run." ) self.assertEqual( unstyle(str(report)), "1 file reformatted, 2 files left unchanged." ) self.assertEqual(report.return_code, 0) report.check = True self.assertEqual(report.return_code, 1) report.check = False report.failed(Path("e1"), "boom") self.assertEqual(len(out_lines), 3) self.assertEqual(len(err_lines), 1) self.assertEqual(err_lines[-1], "error: cannot format e1: boom") self.assertEqual( unstyle(str(report)), "1 file reformatted, 2 files left unchanged, 1 file failed to" " reformat.", ) self.assertEqual(report.return_code, 123) report.done(Path("f3"), black.Changed.YES) self.assertEqual(len(out_lines), 4) self.assertEqual(len(err_lines), 1) self.assertEqual(out_lines[-1], "reformatted f3") self.assertEqual( unstyle(str(report)), "2 files reformatted, 2 files left unchanged, 1 file failed to" " reformat.", ) self.assertEqual(report.return_code, 123) report.failed(Path("e2"), "boom") self.assertEqual(len(out_lines), 4) self.assertEqual(len(err_lines), 2) self.assertEqual(err_lines[-1], "error: cannot format e2: boom") self.assertEqual( unstyle(str(report)), "2 files reformatted, 2 files left unchanged, 2 files failed to" " reformat.", ) self.assertEqual(report.return_code, 123) report.path_ignored(Path("wat"), "no match") self.assertEqual(len(out_lines), 5) self.assertEqual(len(err_lines), 2) self.assertEqual(out_lines[-1], "wat ignored: no match") self.assertEqual( unstyle(str(report)), "2 files reformatted, 2 files left unchanged, 2 files failed to" " reformat.", ) self.assertEqual(report.return_code, 123) report.done(Path("f4"), black.Changed.NO) self.assertEqual(len(out_lines), 6) self.assertEqual(len(err_lines), 2) self.assertEqual(out_lines[-1], "f4 already well formatted, good job.") self.assertEqual( unstyle(str(report)), "2 files reformatted, 3 files left unchanged, 2 files failed to" " reformat.", ) self.assertEqual(report.return_code, 123) report.check = True self.assertEqual( unstyle(str(report)), "2 files would be reformatted, 3 files would be left unchanged, 2" " files would fail to reformat.", ) report.check = False report.diff = True self.assertEqual( unstyle(str(report)), "2 files would be reformatted, 3 files would be left unchanged, 2" " files would fail to reformat.", ) def test_report_quiet(self) -> None: report = Report(quiet=True) out_lines = [] err_lines = [] def out(msg: str, **kwargs: Any) -> None: out_lines.append(msg) def err(msg: str, **kwargs: Any) -> None: err_lines.append(msg) with patch("black.output._out", out), patch("black.output._err", err): report.done(Path("f1"), black.Changed.NO) self.assertEqual(len(out_lines), 0) self.assertEqual(len(err_lines), 0) self.assertEqual(unstyle(str(report)), "1 file left unchanged.") self.assertEqual(report.return_code, 0) report.done(Path("f2"), black.Changed.YES) self.assertEqual(len(out_lines), 0) self.assertEqual(len(err_lines), 0) self.assertEqual( unstyle(str(report)), "1 file reformatted, 1 file left unchanged." ) report.done(Path("f3"), black.Changed.CACHED) self.assertEqual(len(out_lines), 0) self.assertEqual(len(err_lines), 0) self.assertEqual( unstyle(str(report)), "1 file reformatted, 2 files left unchanged." ) self.assertEqual(report.return_code, 0) report.check = True self.assertEqual(report.return_code, 1) report.check = False report.failed(Path("e1"), "boom") self.assertEqual(len(out_lines), 0) self.assertEqual(len(err_lines), 1) self.assertEqual(err_lines[-1], "error: cannot format e1: boom") self.assertEqual( unstyle(str(report)), "1 file reformatted, 2 files left unchanged, 1 file failed to" " reformat.", ) self.assertEqual(report.return_code, 123) report.done(Path("f3"), black.Changed.YES) self.assertEqual(len(out_lines), 0) self.assertEqual(len(err_lines), 1) self.assertEqual( unstyle(str(report)), "2 files reformatted, 2 files left unchanged, 1 file failed to" " reformat.", ) self.assertEqual(report.return_code, 123) report.failed(Path("e2"), "boom") self.assertEqual(len(out_lines), 0) self.assertEqual(len(err_lines), 2) self.assertEqual(err_lines[-1], "error: cannot format e2: boom") self.assertEqual( unstyle(str(report)), "2 files reformatted, 2 files left unchanged, 2 files failed to" " reformat.", ) self.assertEqual(report.return_code, 123) report.path_ignored(Path("wat"), "no match") self.assertEqual(len(out_lines), 0) self.assertEqual(len(err_lines), 2) self.assertEqual( unstyle(str(report)), "2 files reformatted, 2 files left unchanged, 2 files failed to" " reformat.", ) self.assertEqual(report.return_code, 123) report.done(Path("f4"), black.Changed.NO) self.assertEqual(len(out_lines), 0) self.assertEqual(len(err_lines), 2) self.assertEqual( unstyle(str(report)), "2 files reformatted, 3 files left unchanged, 2 files failed to" " reformat.", ) self.assertEqual(report.return_code, 123) report.check = True self.assertEqual( unstyle(str(report)), "2 files would be reformatted, 3 files would be left unchanged, 2" " files would fail to reformat.", ) report.check = False report.diff = True self.assertEqual( unstyle(str(report)), "2 files would be reformatted, 3 files would be left unchanged, 2" " files would fail to reformat.", ) def test_report_normal(self) -> None: report = black.Report() out_lines = [] err_lines = [] def out(msg: str, **kwargs: Any) -> None: out_lines.append(msg) def err(msg: str, **kwargs: Any) -> None: err_lines.append(msg) with patch("black.output._out", out), patch("black.output._err", err): report.done(Path("f1"), black.Changed.NO) self.assertEqual(len(out_lines), 0) self.assertEqual(len(err_lines), 0) self.assertEqual(unstyle(str(report)), "1 file left unchanged.") self.assertEqual(report.return_code, 0) report.done(Path("f2"), black.Changed.YES) self.assertEqual(len(out_lines), 1) self.assertEqual(len(err_lines), 0) self.assertEqual(out_lines[-1], "reformatted f2") self.assertEqual( unstyle(str(report)), "1 file reformatted, 1 file left unchanged." ) report.done(Path("f3"), black.Changed.CACHED) self.assertEqual(len(out_lines), 1) self.assertEqual(len(err_lines), 0) self.assertEqual(out_lines[-1], "reformatted f2") self.assertEqual( unstyle(str(report)), "1 file reformatted, 2 files left unchanged." ) self.assertEqual(report.return_code, 0) report.check = True self.assertEqual(report.return_code, 1) report.check = False report.failed(Path("e1"), "boom") self.assertEqual(len(out_lines), 1) self.assertEqual(len(err_lines), 1) self.assertEqual(err_lines[-1], "error: cannot format e1: boom") self.assertEqual( unstyle(str(report)), "1 file reformatted, 2 files left unchanged, 1 file failed to" " reformat.", ) self.assertEqual(report.return_code, 123) report.done(Path("f3"), black.Changed.YES) self.assertEqual(len(out_lines), 2) self.assertEqual(len(err_lines), 1) self.assertEqual(out_lines[-1], "reformatted f3") self.assertEqual( unstyle(str(report)), "2 files reformatted, 2 files left unchanged, 1 file failed to" " reformat.", ) self.assertEqual(report.return_code, 123) report.failed(Path("e2"), "boom") self.assertEqual(len(out_lines), 2) self.assertEqual(len(err_lines), 2) self.assertEqual(err_lines[-1], "error: cannot format e2: boom") self.assertEqual( unstyle(str(report)), "2 files reformatted, 2 files left unchanged, 2 files failed to" " reformat.", ) self.assertEqual(report.return_code, 123) report.path_ignored(Path("wat"), "no match") self.assertEqual(len(out_lines), 2) self.assertEqual(len(err_lines), 2) self.assertEqual( unstyle(str(report)), "2 files reformatted, 2 files left unchanged, 2 files failed to" " reformat.", ) self.assertEqual(report.return_code, 123) report.done(Path("f4"), black.Changed.NO) self.assertEqual(len(out_lines), 2) self.assertEqual(len(err_lines), 2) self.assertEqual( unstyle(str(report)), "2 files reformatted, 3 files left unchanged, 2 files failed to" " reformat.", ) self.assertEqual(report.return_code, 123) report.check = True self.assertEqual( unstyle(str(report)), "2 files would be reformatted, 3 files would be left unchanged, 2" " files would fail to reformat.", ) report.check = False report.diff = True self.assertEqual( unstyle(str(report)), "2 files would be reformatted, 3 files would be left unchanged, 2" " files would fail to reformat.", ) def test_lib2to3_parse(self) -> None: with self.assertRaises(black.InvalidInput): black.lib2to3_parse("invalid syntax") straddling = "x + y" black.lib2to3_parse(straddling) black.lib2to3_parse(straddling, {TargetVersion.PY36}) py2_only = "print x" with self.assertRaises(black.InvalidInput): black.lib2to3_parse(py2_only, {TargetVersion.PY36}) py3_only = "exec(x, end=y)" black.lib2to3_parse(py3_only) black.lib2to3_parse(py3_only, {TargetVersion.PY36}) def test_get_features_used_decorator(self) -> None: # Test the feature detection of new decorator syntax # since this makes some test cases of test_get_features_used() # fails if it fails, this is tested first so that a useful case # is identified simples, relaxed = read_data("miscellaneous", "decorators") # skip explanation comments at the top of the file for simple_test in simples.split("##")[1:]: node = black.lib2to3_parse(simple_test) decorator = str(node.children[0].children[0]).strip() self.assertNotIn( Feature.RELAXED_DECORATORS,
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
true
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/__init__.py
tests/__init__.py
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/test_schema.py
tests/test_schema.py
import importlib.metadata def test_schema_entrypoint() -> None: (black_ep,) = importlib.metadata.entry_points( group="validate_pyproject.tool_schema", name="black" ) black_fn = black_ep.load() schema = black_fn() assert schema == black_fn("black") assert schema["properties"]["line-length"]["type"] == "integer"
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/test_ranges.py
tests/test_ranges.py
"""Test the black.ranges module.""" import pytest from black.ranges import adjusted_lines, sanitized_lines @pytest.mark.parametrize( "lines", [[(1, 1)], [(1, 3)], [(1, 1), (3, 4)]], ) def test_no_diff(lines: list[tuple[int, int]]) -> None: source = """\ import re def func(): pass """ assert lines == adjusted_lines(lines, source, source) @pytest.mark.parametrize( "lines", [ [(1, 0)], [(-8, 0)], [(-8, 8)], [(1, 100)], [(2, 1)], [(0, 8), (3, 1)], ], ) def test_invalid_lines(lines: list[tuple[int, int]]) -> None: original_source = """\ import re def foo(arg): '''This is the foo function. This is foo function's docstring with more descriptive texts. ''' def func(arg1, arg2, arg3): pass """ modified_source = """\ import re def foo(arg): '''This is the foo function. This is foo function's docstring with more descriptive texts. ''' def func(arg1, arg2, arg3): pass """ assert not adjusted_lines(lines, original_source, modified_source) @pytest.mark.parametrize( "lines,adjusted", [ ( [(1, 1)], [(1, 1)], ), ( [(1, 2)], [(1, 1)], ), ( [(1, 6)], [(1, 2)], ), ( [(6, 6)], [], ), ], ) def test_removals( lines: list[tuple[int, int]], adjusted: list[tuple[int, int]] ) -> None: original_source = """\ 1. first line 2. second line 3. third line 4. fourth line 5. fifth line 6. sixth line """ modified_source = """\ 2. second line 5. fifth line """ assert adjusted == adjusted_lines(lines, original_source, modified_source) @pytest.mark.parametrize( "lines,adjusted", [ ( [(1, 1)], [(2, 2)], ), ( [(1, 2)], [(2, 5)], ), ( [(2, 2)], [(5, 5)], ), ], ) def test_additions( lines: list[tuple[int, int]], adjusted: list[tuple[int, int]] ) -> None: original_source = """\ 1. first line 2. second line """ modified_source = """\ this is added 1. first line this is added this is added 2. second line this is added """ assert adjusted == adjusted_lines(lines, original_source, modified_source) @pytest.mark.parametrize( "lines,adjusted", [ ( [(1, 11)], [(1, 10)], ), ( [(1, 12)], [(1, 11)], ), ( [(10, 10)], [(9, 9)], ), ([(1, 1), (9, 10)], [(1, 1), (9, 9)]), ([(9, 10), (1, 1)], [(1, 1), (9, 9)]), ], ) def test_diffs(lines: list[tuple[int, int]], adjusted: list[tuple[int, int]]) -> None: original_source = """\ 1. import re 2. def foo(arg): 3. '''This is the foo function. 4. 5. This is foo function's 6. docstring with more descriptive texts. 7. ''' 8. 9. def func(arg1, 10. arg2, arg3): 11. pass 12. # last line """ modified_source = """\ 1. import re # changed 2. def foo(arg): 3. '''This is the foo function. 4. 5. This is foo function's 6. docstring with more descriptive texts. 7. ''' 8. 9. def func(arg1, arg2, arg3): 11. pass 12. # last line changed """ assert adjusted == adjusted_lines(lines, original_source, modified_source) @pytest.mark.parametrize( "lines,sanitized", [ ( [(1, 4)], [(1, 4)], ), ( [(2, 3)], [(2, 3)], ), ( [(2, 10)], [(2, 4)], ), ( [(0, 3)], [(1, 3)], ), ( [(0, 10)], [(1, 4)], ), ( [(-2, 3)], [(1, 3)], ), ( [(0, 0)], [], ), ( [(-2, -1)], [], ), ( [(-1, 0)], [], ), ( [(3, 1), (1, 3), (5, 6)], [(1, 3)], ), ], ) def test_sanitize( lines: list[tuple[int, int]], sanitized: list[tuple[int, int]] ) -> None: source = """\ 1. import re 2. def func(arg1, 3. arg2, arg3): 4. pass """ assert sanitized == sanitized_lines(lines, source) source_no_trailing_nl = """\ 1. import re 2. def func(arg1, 3. arg2, arg3): 4. pass""" assert sanitized == sanitized_lines(lines, source_no_trailing_nl)
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/test_blackd.py
tests/test_blackd.py
import gc import re from unittest.mock import patch import pytest from click.testing import CliRunner from tests.util import DETERMINISTIC_HEADER, read_data try: from aiohttp import web from aiohttp.test_utils import AioHTTPTestCase import blackd import blackd.client except ImportError as e: raise RuntimeError("Please install Black with the 'd' extra") from e import black @pytest.mark.blackd class BlackDTestCase(AioHTTPTestCase): def tearDown(self) -> None: # Work around https://github.com/python/cpython/issues/124706 gc.collect() super().tearDown() def test_blackd_main(self) -> None: with patch("blackd.web.run_app"): result = CliRunner().invoke(blackd.main, []) if result.exception is not None: raise result.exception self.assertEqual(result.exit_code, 0) async def get_application(self) -> web.Application: return blackd.make_app() async def test_blackd_request_needs_formatting(self) -> None: response = await self.client.post("/", data=b"print('hello world')") self.assertEqual(response.status, 200) self.assertEqual(response.charset, "utf8") self.assertEqual(await response.read(), b'print("hello world")\n') async def test_blackd_request_no_change(self) -> None: response = await self.client.post("/", data=b'print("hello world")\n') self.assertEqual(response.status, 204) self.assertEqual(await response.read(), b"") async def test_blackd_request_syntax_error(self) -> None: response = await self.client.post("/", data=b"what even ( is") self.assertEqual(response.status, 400) content = await response.text() self.assertTrue( content.startswith("Cannot parse"), msg=f"Expected error to start with 'Cannot parse', got {repr(content)}", ) async def test_blackd_unsupported_version(self) -> None: response = await self.client.post( "/", data=b"what", headers={blackd.PROTOCOL_VERSION_HEADER: "2"} ) self.assertEqual(response.status, 501) async def test_blackd_supported_version(self) -> None: response = await self.client.post( "/", data=b"what", headers={blackd.PROTOCOL_VERSION_HEADER: "1"} ) self.assertEqual(response.status, 200) async def test_blackd_invalid_python_variant(self) -> None: async def check(header_value: str, expected_status: int = 400) -> None: response = await self.client.post( "/", data=b"what", headers={blackd.PYTHON_VARIANT_HEADER: header_value}, ) self.assertEqual(response.status, expected_status) await check("lol") await check("ruby3.5") await check("pyi3.6") await check("py1.5") await check("2") await check("2.7") await check("py2.7") await check("2.8") await check("py2.8") await check("3.0") await check("pypy3.0") await check("jython3.4") async def test_blackd_pyi(self) -> None: source, expected = read_data("cases", "stub.py") response = await self.client.post( "/", data=source, headers={blackd.PYTHON_VARIANT_HEADER: "pyi"} ) self.assertEqual(response.status, 200) self.assertEqual(await response.text(), expected) async def test_blackd_diff(self) -> None: diff_header = re.compile( r"(In|Out)\t\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d\.\d\d\d\d\d\d\+\d\d:\d\d" ) source, _ = read_data("miscellaneous", "blackd_diff") expected, _ = read_data("miscellaneous", "blackd_diff.diff") response = await self.client.post( "/", data=source, headers={blackd.DIFF_HEADER: "true"} ) self.assertEqual(response.status, 200) actual = await response.text() actual = diff_header.sub(DETERMINISTIC_HEADER, actual) self.assertEqual(actual, expected) async def test_blackd_python_variant(self) -> None: code = ( "def f(\n" " and_has_a_bunch_of,\n" " very_long_arguments_too,\n" " and_lots_of_them_as_well_lol,\n" " **and_very_long_keyword_arguments\n" "):\n" " pass\n" ) async def check(header_value: str, expected_status: int) -> None: response = await self.client.post( "/", data=code, headers={blackd.PYTHON_VARIANT_HEADER: header_value} ) self.assertEqual( response.status, expected_status, msg=await response.text() ) await check("3.6", 200) await check("py3.6", 200) await check("3.6,3.7", 200) await check("3.6,py3.7", 200) await check("py36,py37", 200) await check("36", 200) await check("3.6.4", 200) await check("3.4", 204) await check("py3.4", 204) await check("py34,py36", 204) await check("34", 204) async def test_blackd_line_length(self) -> None: response = await self.client.post( "/", data=b'print("hello")\n', headers={blackd.LINE_LENGTH_HEADER: "7"} ) self.assertEqual(response.status, 200) async def test_blackd_invalid_line_length(self) -> None: response = await self.client.post( "/", data=b'print("hello")\n', headers={blackd.LINE_LENGTH_HEADER: "NaN"}, ) self.assertEqual(response.status, 400) async def test_blackd_skip_first_source_line(self) -> None: invalid_first_line = b"Header will be skipped\r\ni = [1,2,3]\nj = [1,2,3]\n" expected_result = b"Header will be skipped\r\ni = [1, 2, 3]\nj = [1, 2, 3]\n" response = await self.client.post("/", data=invalid_first_line) self.assertEqual(response.status, 400) response = await self.client.post( "/", data=invalid_first_line, headers={blackd.SKIP_SOURCE_FIRST_LINE: "true"}, ) self.assertEqual(response.status, 200) self.assertEqual(await response.read(), expected_result) async def test_blackd_preview(self) -> None: response = await self.client.post( "/", data=b'print("hello")\n', headers={blackd.PREVIEW: "true"} ) self.assertEqual(response.status, 204) async def test_blackd_response_black_version_header(self) -> None: response = await self.client.post("/") self.assertIsNotNone(response.headers.get(blackd.BLACK_VERSION_HEADER)) async def test_cors_preflight(self) -> None: response = await self.client.options( "/", headers={ "Access-Control-Request-Method": "POST", "Origin": "*", "Access-Control-Request-Headers": "Content-Type", }, ) self.assertEqual(response.status, 200) self.assertIsNotNone(response.headers.get("Access-Control-Allow-Origin")) self.assertIsNotNone(response.headers.get("Access-Control-Allow-Headers")) self.assertIsNotNone(response.headers.get("Access-Control-Allow-Methods")) async def test_cors_headers_present(self) -> None: response = await self.client.post("/", headers={"Origin": "*"}) self.assertIsNotNone(response.headers.get("Access-Control-Allow-Origin")) self.assertIsNotNone(response.headers.get("Access-Control-Expose-Headers")) async def test_preserves_line_endings(self) -> None: for data in (b"c\r\nc\r\n", b"l\nl\n"): # test preserved newlines when reformatted response = await self.client.post("/", data=data + b" ") self.assertEqual(await response.text(), data.decode()) # test 204 when no change response = await self.client.post("/", data=data) self.assertEqual(response.status, 204) async def test_normalizes_line_endings(self) -> None: for data, expected in ((b"c\r\nc\n", "c\r\nc\r\n"), (b"l\nl\r\n", "l\nl\n")): response = await self.client.post("/", data=data) self.assertEqual(await response.text(), expected) self.assertEqual(response.status, 200) async def test_single_character(self) -> None: response = await self.client.post("/", data="1") self.assertEqual(await response.text(), "1\n") self.assertEqual(response.status, 200) @pytest.mark.blackd class BlackDClientTestCase(AioHTTPTestCase): def tearDown(self) -> None: # Work around https://github.com/python/cpython/issues/124706 gc.collect() super().tearDown() async def get_application(self) -> web.Application: return blackd.make_app() async def test_unformatted_code(self) -> None: client = blackd.client.BlackDClient(self.client.make_url("/")) unformatted_code = "def hello(): print('Hello, World!')" expected = 'def hello():\n print("Hello, World!")\n' formatted_code = await client.format_code(unformatted_code) self.assertEqual(formatted_code, expected) async def test_formatted_code(self) -> None: client = blackd.client.BlackDClient(self.client.make_url("/")) initial_code = 'def hello():\n print("Hello, World!")\n' expected = 'def hello():\n print("Hello, World!")\n' formatted_code = await client.format_code(initial_code) self.assertEqual(formatted_code, expected) async def test_line_length(self) -> None: client = blackd.client.BlackDClient(self.client.make_url("/"), line_length=10) unformatted_code = "def hello(): print('Hello, World!')" expected = 'def hello():\n print(\n "Hello, World!"\n )\n' formatted_code = await client.format_code(unformatted_code) self.assertEqual(formatted_code, expected) async def test_skip_source_first_line(self) -> None: client = blackd.client.BlackDClient( self.client.make_url("/"), skip_source_first_line=True ) invalid_first_line = "Header will be skipped\r\ni = [1,2,3]\nj = [1,2,3]\n" expected_result = "Header will be skipped\r\ni = [1, 2, 3]\nj = [1, 2, 3]\n" formatted_code = await client.format_code(invalid_first_line) self.assertEqual(formatted_code, expected_result) async def test_skip_string_normalization(self) -> None: client = blackd.client.BlackDClient( self.client.make_url("/"), skip_string_normalization=True ) unformatted_code = "def hello(): print('Hello, World!')" expected = "def hello():\n print('Hello, World!')\n" formatted_code = await client.format_code(unformatted_code) self.assertEqual(formatted_code, expected) async def test_skip_magic_trailing_comma(self) -> None: client = blackd.client.BlackDClient( self.client.make_url("/"), skip_magic_trailing_comma=True ) unformatted_code = "def hello(): print('Hello, World!')" expected = 'def hello():\n print("Hello, World!")\n' formatted_code = await client.format_code(unformatted_code) self.assertEqual(formatted_code, expected) async def test_preview(self) -> None: client = blackd.client.BlackDClient(self.client.make_url("/"), preview=True) unformatted_code = "def hello(): print('Hello, World!')" expected = 'def hello():\n print("Hello, World!")\n' formatted_code = await client.format_code(unformatted_code) self.assertEqual(formatted_code, expected) async def test_fast(self) -> None: client = blackd.client.BlackDClient(self.client.make_url("/"), fast=True) unformatted_code = "def hello(): print('Hello, World!')" expected = 'def hello():\n print("Hello, World!")\n' formatted_code = await client.format_code(unformatted_code) self.assertEqual(formatted_code, expected) async def test_python_variant(self) -> None: client = blackd.client.BlackDClient( self.client.make_url("/"), python_variant="3.6" ) unformatted_code = "def hello(): print('Hello, World!')" expected = 'def hello():\n print("Hello, World!")\n' formatted_code = await client.format_code(unformatted_code) self.assertEqual(formatted_code, expected) async def test_diff(self) -> None: diff_header = re.compile( r"(In|Out)\t\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d\.\d\d\d\d\d\d\+\d\d:\d\d" ) client = blackd.client.BlackDClient(self.client.make_url("/"), diff=True) source, _ = read_data("miscellaneous", "blackd_diff") expected, _ = read_data("miscellaneous", "blackd_diff.diff") diff = await client.format_code(source) diff = diff_header.sub(DETERMINISTIC_HEADER, diff) self.assertEqual(diff, expected) async def test_syntax_error(self) -> None: client = blackd.client.BlackDClient(self.client.make_url("/")) with_syntax_error = "def hello(): a 'Hello, World!'" with self.assertRaises(black.InvalidInput): _ = await client.format_code(with_syntax_error)
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/test_no_ipynb.py
tests/test_no_ipynb.py
import pathlib import pytest from click.testing import CliRunner from black import jupyter_dependencies_are_installed, main from tests.util import get_case_path pytestmark = pytest.mark.no_jupyter runner = CliRunner() def test_ipynb_diff_with_no_change_single() -> None: jupyter_dependencies_are_installed.cache_clear() path = get_case_path("jupyter", "notebook_trailing_newline.ipynb") result = runner.invoke(main, [str(path)]) expected_output = ( "Skipping .ipynb files as Jupyter dependencies are not installed.\n" 'You can fix this by running ``pip install "black[jupyter]"``\n' ) assert expected_output in result.output def test_ipynb_diff_with_no_change_dir(tmp_path: pathlib.Path) -> None: jupyter_dependencies_are_installed.cache_clear() runner = CliRunner() nb = get_case_path("jupyter", "notebook_trailing_newline.ipynb") tmp_nb = tmp_path / "notebook.ipynb" tmp_nb.write_bytes(nb.read_bytes()) result = runner.invoke(main, [str(tmp_path)]) expected_output = ( "Skipping .ipynb files as Jupyter dependencies are not installed.\n" 'You can fix this by running ``pip install "black[jupyter]"``\n' ) assert expected_output in result.output
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/remove_await_parens.py
tests/data/cases/remove_await_parens.py
import asyncio # Control example async def main(): await asyncio.sleep(1) # Remove brackets for short coroutine/task async def main(): await (asyncio.sleep(1)) async def main(): await ( asyncio.sleep(1) ) async def main(): await (asyncio.sleep(1) ) # Check comments async def main(): await ( # Hello asyncio.sleep(1) ) async def main(): await ( asyncio.sleep(1) # Hello ) async def main(): await ( asyncio.sleep(1) ) # Hello # Long lines async def main(): await asyncio.gather(asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1)) # Same as above but with magic trailing comma in function async def main(): await asyncio.gather(asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1),) # Cr@zY Br@ck3Tz async def main(): await ( ((((((((((((( ((( ((( ((( ((( ((( ((( ((( ((( ((black(1))) ))) ))) ))) ))) ))) ))) ))) ))) ))))))))))))) ) # Keep brackets around non power operations and nested awaits async def main(): await (set_of_tasks | other_set) async def main(): await (await asyncio.sleep(1)) # It's awaits all the way down... async def main(): await (await x) async def main(): await (yield x) async def main(): await (await (asyncio.sleep(1))) async def main(): await (await (await (await (await (asyncio.sleep(1)))))) async def main(): await (yield) async def main(): await (a ** b) await (a[b] ** c) await (a ** b[c]) await ((a + b) ** (c + d)) await (a + b) await (a[b]) await (a[b ** c]) # output import asyncio # Control example async def main(): await asyncio.sleep(1) # Remove brackets for short coroutine/task async def main(): await asyncio.sleep(1) async def main(): await asyncio.sleep(1) async def main(): await asyncio.sleep(1) # Check comments async def main(): await asyncio.sleep(1) # Hello async def main(): await asyncio.sleep(1) # Hello async def main(): await asyncio.sleep(1) # Hello # Long lines async def main(): await asyncio.gather( asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), ) # Same as above but with magic trailing comma in function async def main(): await asyncio.gather( asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), asyncio.sleep(1), ) # Cr@zY Br@ck3Tz async def main(): await black(1) # Keep brackets around non power operations and nested awaits async def main(): await (set_of_tasks | other_set) async def main(): await (await asyncio.sleep(1)) # It's awaits all the way down... async def main(): await (await x) async def main(): await (yield x) async def main(): await (await asyncio.sleep(1)) async def main(): await (await (await (await (await asyncio.sleep(1))))) async def main(): await (yield) async def main(): await (a**b) await (a[b] ** c) await (a ** b[c]) await ((a + b) ** (c + d)) await (a + b) await a[b] await a[b**c]
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/fmtskip8.py
tests/data/cases/fmtskip8.py
# Make sure a leading comment is not removed. def some_func( unformatted, args ): # fmt: skip print("I am some_func") return 0 # Make sure this comment is not removed. # Make sure a leading comment is not removed. async def some_async_func( unformatted, args): # fmt: skip print("I am some_async_func") await asyncio.sleep(1) # Make sure a leading comment is not removed. class SomeClass( Unformatted, SuperClasses ): # fmt: skip def some_method( self, unformatted, args ): # fmt: skip print("I am some_method") return 0 async def some_async_method( self, unformatted, args ): # fmt: skip print("I am some_async_method") await asyncio.sleep(1) # Make sure a leading comment is not removed. if unformatted_call( args ): # fmt: skip print("First branch") # Make sure this is not removed. elif another_unformatted_call( args ): # fmt: skip print("Second branch") else : # fmt: skip print("Last branch") while some_condition( unformatted, args ): # fmt: skip print("Do something") for i in some_iter( unformatted, args ): # fmt: skip print("Do something") async def test_async_for(): async for i in some_async_iter( unformatted, args ): # fmt: skip print("Do something") try : # fmt: skip some_call() except UnformattedError as ex: # fmt: skip handle_exception() finally : # fmt: skip finally_call() with give_me_context( unformatted, args ): # fmt: skip print("Do something") async def test_async_with(): async with give_me_async_context( unformatted, args ): # fmt: skip print("Do something")
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/trailing_comma_optional_parens1.py
tests/data/cases/trailing_comma_optional_parens1.py
if e1234123412341234.winerror not in (_winapi.ERROR_SEM_TIMEOUT, _winapi.ERROR_PIPE_BUSY) or _check_timeout(t): pass if x: if y: new_id = max(Vegetable.objects.order_by('-id')[0].id, Mineral.objects.order_by('-id')[0].id) + 1 class X: def get_help_text(self): return ngettext( "Your password must contain at least %(min_length)d character.", "Your password must contain at least %(min_length)d characters.", self.min_length, ) % {'min_length': self.min_length} class A: def b(self): if self.connection.mysql_is_mariadb and ( 10, 4, 3, ) < self.connection.mysql_version < (10, 5, 2): pass # output if e1234123412341234.winerror not in ( _winapi.ERROR_SEM_TIMEOUT, _winapi.ERROR_PIPE_BUSY, ) or _check_timeout(t): pass if x: if y: new_id = ( max( Vegetable.objects.order_by("-id")[0].id, Mineral.objects.order_by("-id")[0].id, ) + 1 ) class X: def get_help_text(self): return ngettext( "Your password must contain at least %(min_length)d character.", "Your password must contain at least %(min_length)d characters.", self.min_length, ) % {"min_length": self.min_length} class A: def b(self): if self.connection.mysql_is_mariadb and ( 10, 4, 3, ) < self.connection.mysql_version < (10, 5, 2): pass
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/pep_572_do_not_remove_parens.py
tests/data/cases/pep_572_do_not_remove_parens.py
# flags: --fast # Most of the following examples are really dumb, some of them aren't even accepted by Python, # we're fixing them only so fuzzers (which follow the grammar which actually allows these # examples matter of fact!) don't yell at us :p del (a := [1]) try: pass except (a := 1) as (b := why_does_this_exist): pass for (z := 124) in (x := -124): pass with (y := [3, 2, 1]) as (funfunfun := indeed): pass @(please := stop) def sigh(): pass for (x := 3, y := 4) in y: pass
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/format_unicode_escape_seq.py
tests/data/cases/format_unicode_escape_seq.py
x = "\x1F" x = "\\x1B" x = "\\\x1B" x = "\U0001F60E" x = "\u0001F60E" x = r"\u0001F60E" x = "don't format me" x = "\xA3" x = "\u2717" x = "\uFaCe" x = "\N{ox}\N{OX}" x = "\N{lAtIn smaLL letteR x}" x = "\N{CYRILLIC small LETTER BYELORUSSIAN-UKRAINIAN I}" x = b"\x1Fdon't byte" x = rb"\x1Fdon't format" # output x = "\x1f" x = "\\x1B" x = "\\\x1b" x = "\U0001f60e" x = "\u0001F60E" x = r"\u0001F60E" x = "don't format me" x = "\xa3" x = "\u2717" x = "\uface" x = "\N{OX}\N{OX}" x = "\N{LATIN SMALL LETTER X}" x = "\N{CYRILLIC SMALL LETTER BYELORUSSIAN-UKRAINIAN I}" x = b"\x1fdon't byte" x = rb"\x1Fdon't format"
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/comments_in_double_parens.py
tests/data/cases/comments_in_double_parens.py
if ( True # sdf ): print("hw") if (( True # sdf )): print("hw") if (( # type: ignore True )): print("hw") if (( True # type: ignore )): print("hw") if ( # a long comment about # the condition below (a or b) ): pass def return_true(): return ( ( True # this comment gets removed accidentally ) ) def return_true(): return (True) # this comment gets removed accidentally if ( # huh comment (True) ): ... if ( # huh ( # comment True ) ): ... # output if ( True # sdf ): print("hw") if ( True # sdf ): print("hw") if ( # type: ignore True ): print("hw") if ( True # type: ignore ): print("hw") if ( # a long comment about # the condition below a or b ): pass def return_true(): return True # this comment gets removed accidentally def return_true(): return True # this comment gets removed accidentally if ( # huh comment True ): ... if ( # huh # comment True ): ...
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/power_op_spacing.py
tests/data/cases/power_op_spacing.py
def function(**kwargs): t = a**2 + b**3 return t ** 2 def function_replace_spaces(**kwargs): t = a **2 + b** 3 + c ** 4 def function_dont_replace_spaces(): {**a, **b, **c} a = 5**~4 b = 5 ** f() c = -(5**2) d = 5 ** f["hi"] e = lazy(lambda **kwargs: 5) f = f() ** 5 g = a.b**c.d h = 5 ** funcs.f() i = funcs.f() ** 5 j = super().name ** 5 k = [(2**idx, value) for idx, value in pairs] l = mod.weights_[0] == pytest.approx(0.95**100, abs=0.001) m = [([2**63], [1, 2**63])] n = count <= 10**5 o = settings(max_examples=10**6) p = {(k, k**2): v**2 for k, v in pairs} q = [10**i for i in range(6)] r = x**y s = 1 ** 1 t = ( 1 ** 1 **1 ** 1 ) a = 5.0**~4.0 b = 5.0 ** f() c = -(5.0**2.0) d = 5.0 ** f["hi"] e = lazy(lambda **kwargs: 5) f = f() ** 5.0 g = a.b**c.d h = 5.0 ** funcs.f() i = funcs.f() ** 5.0 j = super().name ** 5.0 k = [(2.0**idx, value) for idx, value in pairs] l = mod.weights_[0] == pytest.approx(0.95**100, abs=0.001) m = [([2.0**63.0], [1.0, 2**63.0])] n = count <= 10**5.0 o = settings(max_examples=10**6.0) p = {(k, k**2): v**2.0 for k, v in pairs} q = [10.5**i for i in range(6)] s = 1.0 ** 1.0 t = ( 1.0 ** 1.0 **1.0 ** 1.0 ) # WE SHOULD DEFINITELY NOT EAT THESE COMMENTS (https://github.com/psf/black/issues/2873) if hasattr(view, "sum_of_weights"): return np.divide( # type: ignore[no-any-return] view.variance, # type: ignore[union-attr] view.sum_of_weights, # type: ignore[union-attr] out=np.full(view.sum_of_weights.shape, np.nan), # type: ignore[union-attr] where=view.sum_of_weights**2 > view.sum_of_weights_squared, # type: ignore[union-attr] ) return np.divide( where=view.sum_of_weights_of_weight_long**2 > view.sum_of_weights_squared, # type: ignore ) # output def function(**kwargs): t = a**2 + b**3 return t**2 def function_replace_spaces(**kwargs): t = a**2 + b**3 + c**4 def function_dont_replace_spaces(): {**a, **b, **c} a = 5**~4 b = 5 ** f() c = -(5**2) d = 5 ** f["hi"] e = lazy(lambda **kwargs: 5) f = f() ** 5 g = a.b**c.d h = 5 ** funcs.f() i = funcs.f() ** 5 j = super().name ** 5 k = [(2**idx, value) for idx, value in pairs] l = mod.weights_[0] == pytest.approx(0.95**100, abs=0.001) m = [([2**63], [1, 2**63])] n = count <= 10**5 o = settings(max_examples=10**6) p = {(k, k**2): v**2 for k, v in pairs} q = [10**i for i in range(6)] r = x**y s = 1**1 t = 1**1**1**1 a = 5.0**~4.0 b = 5.0 ** f() c = -(5.0**2.0) d = 5.0 ** f["hi"] e = lazy(lambda **kwargs: 5) f = f() ** 5.0 g = a.b**c.d h = 5.0 ** funcs.f() i = funcs.f() ** 5.0 j = super().name ** 5.0 k = [(2.0**idx, value) for idx, value in pairs] l = mod.weights_[0] == pytest.approx(0.95**100, abs=0.001) m = [([2.0**63.0], [1.0, 2**63.0])] n = count <= 10**5.0 o = settings(max_examples=10**6.0) p = {(k, k**2): v**2.0 for k, v in pairs} q = [10.5**i for i in range(6)] s = 1.0**1.0 t = 1.0**1.0**1.0**1.0 # WE SHOULD DEFINITELY NOT EAT THESE COMMENTS (https://github.com/psf/black/issues/2873) if hasattr(view, "sum_of_weights"): return np.divide( # type: ignore[no-any-return] view.variance, # type: ignore[union-attr] view.sum_of_weights, # type: ignore[union-attr] out=np.full(view.sum_of_weights.shape, np.nan), # type: ignore[union-attr] where=view.sum_of_weights**2 > view.sum_of_weights_squared, # type: ignore[union-attr] ) return np.divide( where=view.sum_of_weights_of_weight_long**2 > view.sum_of_weights_squared, # type: ignore )
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/line_ranges_fmt_off.py
tests/data/cases/line_ranges_fmt_off.py
# flags: --line-ranges=7-7 --line-ranges=17-23 # NOTE: If you need to modify this file, pay special attention to the --line-ranges= # flag above as it's formatting specifically these lines. # fmt: off import os def myfunc( ): # Intentionally unformatted. pass # fmt: on def myfunc( ): # This will not be reformatted. print( {"also won't be reformatted"} ) # fmt: off def myfunc( ): # This will not be reformatted. print( {"also won't be reformatted"} ) def myfunc( ): # This will not be reformatted. print( {"also won't be reformatted"} ) # fmt: on def myfunc( ): # This will be reformatted. print( {"this will be reformatted"} ) # output # flags: --line-ranges=7-7 --line-ranges=17-23 # NOTE: If you need to modify this file, pay special attention to the --line-ranges= # flag above as it's formatting specifically these lines. # fmt: off import os def myfunc( ): # Intentionally unformatted. pass # fmt: on def myfunc( ): # This will not be reformatted. print( {"also won't be reformatted"} ) # fmt: off def myfunc( ): # This will not be reformatted. print( {"also won't be reformatted"} ) def myfunc( ): # This will not be reformatted. print( {"also won't be reformatted"} ) # fmt: on def myfunc(): # This will be reformatted. print({"this will be reformatted"})
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/fmtonoff5.py
tests/data/cases/fmtonoff5.py
# Regression test for https://github.com/psf/black/issues/3129. setup( entry_points={ # fmt: off "console_scripts": [ "foo-bar" "=foo.bar.:main", # fmt: on ] # Includes an formatted indentation. }, ) # Regression test for https://github.com/psf/black/issues/2015. run( # fmt: off [ "ls", "-la", ] # fmt: on + path, check=True, ) # Regression test for https://github.com/psf/black/issues/3026. def test_func(): # yapf: disable if unformatted( args ): return True # yapf: enable elif b: return True return False # Regression test for https://github.com/psf/black/issues/2567. if True: # fmt: off for _ in range( 1 ): # fmt: on print ( "This won't be formatted" ) print ( "This won't be formatted either" ) else: print ( "This will be formatted" ) # Regression test for https://github.com/psf/black/issues/3184. class A: async def call(param): if param: # fmt: off if param[0:4] in ( "ABCD", "EFGH" ) : # fmt: on print ( "This won't be formatted" ) elif param[0:4] in ("ZZZZ",): print ( "This won't be formatted either" ) print ( "This will be formatted" ) # Regression test for https://github.com/psf/black/issues/2985. class Named(t.Protocol): # fmt: off @property def this_wont_be_formatted ( self ) -> str: ... class Factory(t.Protocol): def this_will_be_formatted ( self, **kwargs ) -> Named: ... # fmt: on # Regression test for https://github.com/psf/black/issues/3436. if x: return x # fmt: off elif unformatted: # fmt: on will_be_formatted () # output # Regression test for https://github.com/psf/black/issues/3129. setup( entry_points={ # fmt: off "console_scripts": [ "foo-bar" "=foo.bar.:main", # fmt: on ] # Includes an formatted indentation. }, ) # Regression test for https://github.com/psf/black/issues/2015. run( # fmt: off [ "ls", "-la", ] # fmt: on + path, check=True, ) # Regression test for https://github.com/psf/black/issues/3026. def test_func(): # yapf: disable if unformatted( args ): return True # yapf: enable elif b: return True return False # Regression test for https://github.com/psf/black/issues/2567. if True: # fmt: off for _ in range( 1 ): # fmt: on print ( "This won't be formatted" ) print ( "This won't be formatted either" ) else: print("This will be formatted") # Regression test for https://github.com/psf/black/issues/3184. class A: async def call(param): if param: # fmt: off if param[0:4] in ( "ABCD", "EFGH" ) : # fmt: on print ( "This won't be formatted" ) elif param[0:4] in ("ZZZZ",): print ( "This won't be formatted either" ) print("This will be formatted") # Regression test for https://github.com/psf/black/issues/2985. class Named(t.Protocol): # fmt: off @property def this_wont_be_formatted ( self ) -> str: ... class Factory(t.Protocol): def this_will_be_formatted(self, **kwargs) -> Named: ... # fmt: on # Regression test for https://github.com/psf/black/issues/3436. if x: return x # fmt: off elif unformatted: # fmt: on will_be_formatted()
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/comments6.py
tests/data/cases/comments6.py
from typing import Any, Tuple def f( a, # type: int ): pass # test type comments def f(a, b, c, d, e, f, g, h, i): # type: (int, int, int, int, int, int, int, int, int) -> None pass def f( a, # type: int b, # type: int c, # type: int d, # type: int e, # type: int f, # type: int g, # type: int h, # type: int i, # type: int ): # type: (...) -> None pass def f( arg, # type: int *args, # type: *Any default=False, # type: bool **kwargs, # type: **Any ): # type: (...) -> None pass def f( a, # type: int b, # type: int c, # type: int d, # type: int ): # type: (...) -> None element = 0 # type: int another_element = 1 # type: float another_element_with_long_name = 2 # type: int another_really_really_long_element_with_a_unnecessarily_long_name_to_describe_what_it_does_enterprise_style = ( 3 ) # type: int an_element_with_a_long_value = calls() or more_calls() and more() # type: bool tup = ( another_element, another_really_really_long_element_with_a_unnecessarily_long_name_to_describe_what_it_does_enterprise_style, ) # type: Tuple[int, int] a = ( element + another_element + another_element_with_long_name + element + another_element + another_element_with_long_name ) # type: int def f( x, # not a type comment y, # type: int ): # type: (...) -> None pass def f( x, # not a type comment ): # type: (int) -> None pass def func( a=some_list[0], # type: int ): # type: () -> int c = call( 0.0123, 0.0456, 0.0789, 0.0123, 0.0456, 0.0789, 0.0123, 0.0456, 0.0789, a[-1], # type: ignore ) c = call( "aaaaaaaa", "aaaaaaaa", "aaaaaaaa", "aaaaaaaa", "aaaaaaaa", "aaaaaaaa", "aaaaaaaa" # type: ignore ) result = ( # aaa "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" ) AAAAAAAAAAAAA = [AAAAAAAAAAAAA] + SHARED_AAAAAAAAAAAAA + USER_AAAAAAAAAAAAA + AAAAAAAAAAAAA # type: ignore call_to_some_function_asdf( foo, [AAAAAAAAAAAAAAAAAAAAAAA, AAAAAAAAAAAAAAAAAAAAAAA, AAAAAAAAAAAAAAAAAAAAAAA, BBBBBBBBBBBB], # type: ignore ) aaaaaaaaaaaaa, bbbbbbbbb = map(list, map(itertools.chain.from_iterable, zip(*items))) # type: ignore[arg-type]
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/line_ranges_fmt_off_decorator.py
tests/data/cases/line_ranges_fmt_off_decorator.py
# flags: --line-ranges=12-12 --line-ranges=21-21 # NOTE: If you need to modify this file, pay special attention to the --line-ranges= # flag above as it's formatting specifically these lines. # Regression test for an edge case involving decorators and fmt: off/on. class MyClass: # fmt: off @decorator ( ) # fmt: on def method(): print ( "str" ) @decor( a=1, # fmt: off b=(2, 3), # fmt: on ) def func(): pass # output # flags: --line-ranges=12-12 --line-ranges=21-21 # NOTE: If you need to modify this file, pay special attention to the --line-ranges= # flag above as it's formatting specifically these lines. # Regression test for an edge case involving decorators and fmt: off/on. class MyClass: # fmt: off @decorator ( ) # fmt: on def method(): print("str") @decor( a=1, # fmt: off b=(2, 3), # fmt: on ) def func(): pass
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/return_annotation_brackets.py
tests/data/cases/return_annotation_brackets.py
# Control def double(a: int) -> int: return 2*a # Remove the brackets def double(a: int) -> (int): return 2*a # Some newline variations def double(a: int) -> ( int): return 2*a def double(a: int) -> (int ): return 2*a def double(a: int) -> ( int ): return 2*a # Don't lose the comments def double(a: int) -> ( # Hello int ): return 2*a def double(a: int) -> ( int # Hello ): return 2*a # Really long annotations def foo() -> ( intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds ): return 2 def foo() -> intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds: return 2 def foo() -> intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds | intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds: return 2 def foo(a: int, b: int, c: int,) -> intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds: return 2 def foo(a: int, b: int, c: int,) -> intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds | intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds: return 2 # Split args but no need to split return def foo(a: int, b: int, c: int,) -> int: return 2 # Deeply nested brackets # with *interesting* spacing def double(a: int) -> (((((int))))): return 2*a def double(a: int) -> ( ( ( ((int) ) ) ) ): return 2*a def foo() -> ( ( ( intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds ) )): return 2 # Return type with commas def foo() -> ( tuple[int, int, int] ): return 2 def foo() -> tuple[loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong, loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong, loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong]: return 2 # Magic trailing comma example def foo() -> tuple[int, int, int,]: return 2 # Magic trailing comma example, with params def foo(a,b) -> tuple[int, int, int,]: return 2 # output # Control def double(a: int) -> int: return 2 * a # Remove the brackets def double(a: int) -> int: return 2 * a # Some newline variations def double(a: int) -> int: return 2 * a def double(a: int) -> int: return 2 * a def double(a: int) -> int: return 2 * a # Don't lose the comments def double(a: int) -> int: # Hello return 2 * a def double(a: int) -> int: # Hello return 2 * a # Really long annotations def foo() -> ( intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds ): return 2 def foo() -> ( intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds ): return 2 def foo() -> ( intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds | intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds ): return 2 def foo( a: int, b: int, c: int, ) -> intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds: return 2 def foo( a: int, b: int, c: int, ) -> ( intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds | intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds ): return 2 # Split args but no need to split return def foo( a: int, b: int, c: int, ) -> int: return 2 # Deeply nested brackets # with *interesting* spacing def double(a: int) -> int: return 2 * a def double(a: int) -> int: return 2 * a def foo() -> ( intsdfsafafafdfdsasdfsfsdfasdfafdsafdfdsfasdskdsdsfdsafdsafsdfdasfffsfdsfdsafafhdskfhdsfjdslkfdlfsdkjhsdfjkdshfkljds ): return 2 # Return type with commas def foo() -> tuple[int, int, int]: return 2 def foo() -> tuple[ loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong, loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong, loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong, ]: return 2 # Magic trailing comma example def foo() -> tuple[ int, int, int, ]: return 2 # Magic trailing comma example, with params def foo(a, b) -> tuple[ int, int, int, ]: return 2
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/line_ranges_diff_edge_case.py
tests/data/cases/line_ranges_diff_edge_case.py
# flags: --line-ranges=10-11 # NOTE: If you need to modify this file, pay special attention to the --line-ranges= # flag above as it's formatting specifically these lines. # Reproducible example for https://github.com/psf/black/issues/4033. # This can be fixed in the future if we use a better diffing algorithm, or make Black # perform formatting in a single pass. print ( "format me" ) print ( "format me" ) print ( "format me" ) print ( "format me" ) print ( "format me" ) # output # flags: --line-ranges=10-11 # NOTE: If you need to modify this file, pay special attention to the --line-ranges= # flag above as it's formatting specifically these lines. # Reproducible example for https://github.com/psf/black/issues/4033. # This can be fixed in the future if we use a better diffing algorithm, or make Black # perform formatting in a single pass. print ( "format me" ) print("format me") print("format me") print("format me") print("format me")
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/is_simple_lookup_for_doublestar_expression.py
tests/data/cases/is_simple_lookup_for_doublestar_expression.py
m2 = None if not isinstance(dist, Normal) else m** 2 + s * 2 m3 = None if not isinstance(dist, Normal) else m ** 2 + s * 2 m4 = None if not isinstance(dist, Normal) else m**2 + s * 2 m5 = obj.method(another_obj.method()).attribute **2 m6 = None if ... else m**2 + s**2 # output m2 = None if not isinstance(dist, Normal) else m**2 + s * 2 m3 = None if not isinstance(dist, Normal) else m**2 + s * 2 m4 = None if not isinstance(dist, Normal) else m**2 + s * 2 m5 = obj.method(another_obj.method()).attribute ** 2 m6 = None if ... else m**2 + s**2
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/pattern_matching_style.py
tests/data/cases/pattern_matching_style.py
# flags: --minimum-version=3.10 match something: case b(): print(1+1) case c( very_complex=True, perhaps_even_loooooooooooooooooooooooooooooooooooooong=- 1 ): print(1) case c( very_complex=True, perhaps_even_loooooooooooooooooooooooooooooooooooooong=-1, ): print(2) case a: pass match( arg # comment ) match( ) match( ) case( arg # comment ) case( ) case( ) re.match( something # fast ) re.match( ) match match( ): case case( arg, # comment ): pass # output match something: case b(): print(1 + 1) case c( very_complex=True, perhaps_even_loooooooooooooooooooooooooooooooooooooong=-1 ): print(1) case c( very_complex=True, perhaps_even_loooooooooooooooooooooooooooooooooooooong=-1, ): print(2) case a: pass match(arg) # comment match() match() case(arg) # comment case() case() re.match(something) # fast re.match() match match(): case case( arg, # comment ): pass
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/pattern_matching_simple.py
tests/data/cases/pattern_matching_simple.py
# flags: --minimum-version=3.10 # Cases sampled from PEP 636 examples match command.split(): case [action, obj]: ... # interpret action, obj match command.split(): case [action]: ... # interpret single-verb action case [action, obj]: ... # interpret action, obj match command.split(): case ["quit"]: print("Goodbye!") quit_game() case ["look"]: current_room.describe() case ["get", obj]: character.get(obj, current_room) case ["go", direction]: current_room = current_room.neighbor(direction) # The rest of your commands go here match command.split(): case ["drop", *objects]: for obj in objects: character.drop(obj, current_room) # The rest of your commands go here match command.split(): case ["quit"]: pass case ["go", direction]: print("Going:", direction) case ["drop", *objects]: print("Dropping: ", *objects) case _: print(f"Sorry, I couldn't understand {command!r}") match command.split(): case ["north"] | ["go", "north"]: current_room = current_room.neighbor("north") case ["get", obj] | ["pick", "up", obj] | ["pick", obj, "up"]: ... # Code for picking up the given object match command.split(): case ["go", ("north" | "south" | "east" | "west")]: current_room = current_room.neighbor(...) # how do I know which direction to go? match command.split(): case ["go", ("north" | "south" | "east" | "west") as direction]: current_room = current_room.neighbor(direction) match command.split(): case ["go", direction] if direction in current_room.exits: current_room = current_room.neighbor(direction) case ["go", _]: print("Sorry, you can't go that way") match event.get(): case Click(position=(x, y)): handle_click_at(x, y) case KeyPress(key_name="Q") | Quit(): game.quit() case KeyPress(key_name="up arrow"): game.go_north() case KeyPress(): pass # Ignore other keystrokes case other_event: raise ValueError(f"Unrecognized event: {other_event}") match event.get(): case Click((x, y), button=Button.LEFT): # This is a left click handle_click_at(x, y) case Click(): pass # ignore other clicks def where_is(point): match point: case Point(x=0, y=0): print("Origin") case Point(x=0, y=y): print(f"Y={y}") case Point(x=x, y=0): print(f"X={x}") case Point(): print("Somewhere else") case _: print("Not a point")
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/bytes_docstring.py
tests/data/cases/bytes_docstring.py
def bitey(): b" not a docstring" def bitey2(): b' also not a docstring' def triple_quoted_bytes(): b""" not a docstring""" def triple_quoted_bytes2(): b''' also not a docstring''' def capitalized_bytes(): B" NOT A DOCSTRING" # output def bitey(): b" not a docstring" def bitey2(): b" also not a docstring" def triple_quoted_bytes(): b""" not a docstring""" def triple_quoted_bytes2(): b""" also not a docstring""" def capitalized_bytes(): b" NOT A DOCSTRING"
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/dummy_implementations.py
tests/data/cases/dummy_implementations.py
from typing import NoReturn, Protocol, Union, overload class Empty: ... def dummy(a): ... async def other(b): ... @overload def a(arg: int) -> int: ... @overload def a(arg: str) -> str: ... @overload def a(arg: object) -> NoReturn: ... def a(arg: Union[int, str, object]) -> Union[int, str]: if not isinstance(arg, (int, str)): raise TypeError return arg class Proto(Protocol): def foo(self, a: int) -> int: ... def bar(self, b: str) -> str: ... def baz(self, c: bytes) -> str: ... def dummy_two(): ... @dummy def dummy_three(): ... def dummy_four(): ... @overload def b(arg: int) -> int: ... @overload def b(arg: str) -> str: ... @overload def b(arg: object) -> NoReturn: ... def b(arg: Union[int, str, object]) -> Union[int, str]: if not isinstance(arg, (int, str)): raise TypeError return arg def has_comment(): ... # still a dummy if some_condition: ... if already_dummy: ... class AsyncCls: async def async_method(self): ... async def async_function(self): ... @decorated async def async_function(self): ... class ClassA: def f(self): ... class ClassB: def f(self): ... class ClassC: def f(self): ... # Comment class ClassD: def f(self):# Comment 1 ...# Comment 2 # Comment 3 class ClassE: def f(self): ... def f2(self): print(10) class ClassF: def f(self): ...# Comment 2 class ClassG: def f(self):#Comment 1 ...# Comment 2 class ClassH: def f(self): #Comment ... # output from typing import NoReturn, Protocol, Union, overload class Empty: ... def dummy(a): ... async def other(b): ... @overload def a(arg: int) -> int: ... @overload def a(arg: str) -> str: ... @overload def a(arg: object) -> NoReturn: ... def a(arg: Union[int, str, object]) -> Union[int, str]: if not isinstance(arg, (int, str)): raise TypeError return arg class Proto(Protocol): def foo(self, a: int) -> int: ... def bar(self, b: str) -> str: ... def baz(self, c: bytes) -> str: ... def dummy_two(): ... @dummy def dummy_three(): ... def dummy_four(): ... @overload def b(arg: int) -> int: ... @overload def b(arg: str) -> str: ... @overload def b(arg: object) -> NoReturn: ... def b(arg: Union[int, str, object]) -> Union[int, str]: if not isinstance(arg, (int, str)): raise TypeError return arg def has_comment(): ... # still a dummy if some_condition: ... if already_dummy: ... class AsyncCls: async def async_method(self): ... async def async_function(self): ... @decorated async def async_function(self): ... class ClassA: def f(self): ... class ClassB: def f(self): ... class ClassC: def f(self): ... # Comment class ClassD: def f(self): # Comment 1 ... # Comment 2 # Comment 3 class ClassE: def f(self): ... def f2(self): print(10) class ClassF: def f(self): ... # Comment 2 class ClassG: def f(self): # Comment 1 ... # Comment 2 class ClassH: def f(self): # Comment ...
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/module_docstring_1.py
tests/data/cases/module_docstring_1.py
"""Single line module-level docstring should be followed by single newline.""" a = 1 """I'm just a string so should be followed by 2 newlines.""" b = 2 # output """Single line module-level docstring should be followed by single newline.""" a = 1 """I'm just a string so should be followed by 2 newlines.""" b = 2
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/fmtskip12.py
tests/data/cases/fmtskip12.py
# flags: --preview with open("file.txt") as f: content = f.read() # fmt: skip # Ideally, only the last line would be ignored # But ignoring only part of the asexpr_test causes a parse error # Same with ignoring the asexpr_test without also ignoring the entire with_stmt with open ( "file.txt" , ) as f: content = f.read() # fmt: skip # output with open("file.txt") as f: content = f.read() # fmt: skip # Ideally, only the last line would be ignored # But ignoring only part of the asexpr_test causes a parse error # Same with ignoring the asexpr_test without also ignoring the entire with_stmt with open ( "file.txt" , ) as f: content = f.read() # fmt: skip
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/comment_type_hint.py
tests/data/cases/comment_type_hint.py
# flags: --no-preview-line-length-1 # split out from comments2 as it does not work with line-length=1, losing the comment a = "type comment with trailing space" # type: str
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/pattern_matching_long.py
tests/data/cases/pattern_matching_long.py
# flags: --minimum-version=3.10 match x: case "abcd" | "abcd" | "abcd" : pass case "abcd" | "abcd" | "abcd" | "abcd" | "abcd" | "abcd" | "abcd" | "abcd" | "abcd" | "abcd" | "abcd" | "abcd" | "abcd" | "abcd" | "abcd": pass case xxxxxxxxxxxxxxxxxxxxxxx: pass # output match x: case "abcd" | "abcd" | "abcd": pass case ( "abcd" | "abcd" | "abcd" | "abcd" | "abcd" | "abcd" | "abcd" | "abcd" | "abcd" | "abcd" | "abcd" | "abcd" | "abcd" | "abcd" | "abcd" ): pass case xxxxxxxxxxxxxxxxxxxxxxx: pass
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/context_managers_autodetect_39.py
tests/data/cases/context_managers_autodetect_39.py
# This file uses parenthesized context managers introduced in Python 3.9. with \ make_context_manager1() as cm1, \ make_context_manager2() as cm2, \ make_context_manager3() as cm3, \ make_context_manager4() as cm4 \ : pass with ( new_new_new1() as cm1, new_new_new2() ): pass # output # This file uses parenthesized context managers introduced in Python 3.9. with ( make_context_manager1() as cm1, make_context_manager2() as cm2, make_context_manager3() as cm3, make_context_manager4() as cm4, ): pass with new_new_new1() as cm1, new_new_new2(): pass
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/attribute_access_on_number_literals.py
tests/data/cases/attribute_access_on_number_literals.py
x = 123456789 .bit_count() x = (123456).__abs__() x = .1.is_integer() x = 1. .imag x = 1E+1.imag x = 1E-1.real x = 123456789.123456789.hex() x = 123456789.123456789E123456789 .real x = 123456789E123456789 .conjugate() x = 123456789J.real x = 123456789.123456789J.__add__(0b1011.bit_length()) x = 0XB1ACC.conjugate() x = 0B1011 .conjugate() x = 0O777 .real x = 0.000000006 .hex() x = -100.0000J if 10 .real: ... y = 100[no] y = 100(no) # output x = (123456789).bit_count() x = (123456).__abs__() x = (0.1).is_integer() x = (1.0).imag x = (1e1).imag x = (1e-1).real x = (123456789.123456789).hex() x = (123456789.123456789e123456789).real x = (123456789e123456789).conjugate() x = 123456789j.real x = 123456789.123456789j.__add__(0b1011.bit_length()) x = 0xB1ACC.conjugate() x = 0b1011.conjugate() x = 0o777.real x = (0.000000006).hex() x = -100.0000j if (10).real: ... y = 100[no] y = 100(no)
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/tuple_with_stmt.py
tests/data/cases/tuple_with_stmt.py
# don't remove the brackets here, it changes the meaning of the code. # even though the code will always trigger a runtime error with (name_5, name_4), name_5: pass with c, (a, b): pass with c, (a, b), d: pass with c, (a, b, e, f, g), d: pass def test_tuple_as_contextmanager(): from contextlib import nullcontext try: with (nullcontext(), nullcontext()), nullcontext(): pass except TypeError: # test passed pass else: # this should be a type error assert False
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/bracketmatch.py
tests/data/cases/bracketmatch.py
for ((x in {}) or {})['a'] in x: pass pem_spam = lambda l, spam = { "x": 3 }: not spam.get(l.strip()) lambda x=lambda y={1: 3}: y['x':lambda y: {1: 2}]: x # output for ((x in {}) or {})["a"] in x: pass pem_spam = lambda l, spam={"x": 3}: not spam.get(l.strip()) lambda x=lambda y={1: 3}: y["x" : lambda y: {1: 2}]: x
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/import_spacing.py
tests/data/cases/import_spacing.py
"""The asyncio package, tracking PEP 3156.""" # flake8: noqa from logging import ( WARNING ) from logging import ( ERROR, ) import sys # This relies on each of the submodules having an __all__ variable. from .base_events import * from .coroutines import * from .events import * # comment here from .futures import * from .locks import * # comment here from .protocols import * from ..runners import * # comment here from ..queues import * from ..streams import * from some_library import ( Just, Enough, Libraries, To, Fit, In, This, Nice, Split, Which, We, No, Longer, Use ) from name_of_a_company.extremely_long_project_name.component.ttypes import CuteLittleServiceHandlerFactoryyy from name_of_a_company.extremely_long_project_name.extremely_long_component_name.ttypes import * from .a.b.c.subprocess import * from . import (tasks) from . import (A, B, C) from . import SomeVeryLongNameAndAllOfItsAdditionalLetters1, \ SomeVeryLongNameAndAllOfItsAdditionalLetters2 __all__ = ( base_events.__all__ + coroutines.__all__ + events.__all__ + futures.__all__ + locks.__all__ + protocols.__all__ + runners.__all__ + queues.__all__ + streams.__all__ + tasks.__all__ ) # output """The asyncio package, tracking PEP 3156.""" # flake8: noqa from logging import WARNING from logging import ( ERROR, ) import sys # This relies on each of the submodules having an __all__ variable. from .base_events import * from .coroutines import * from .events import * # comment here from .futures import * from .locks import * # comment here from .protocols import * from ..runners import * # comment here from ..queues import * from ..streams import * from some_library import ( Just, Enough, Libraries, To, Fit, In, This, Nice, Split, Which, We, No, Longer, Use, ) from name_of_a_company.extremely_long_project_name.component.ttypes import ( CuteLittleServiceHandlerFactoryyy, ) from name_of_a_company.extremely_long_project_name.extremely_long_component_name.ttypes import * from .a.b.c.subprocess import * from . import tasks from . import A, B, C from . import ( SomeVeryLongNameAndAllOfItsAdditionalLetters1, SomeVeryLongNameAndAllOfItsAdditionalLetters2, ) __all__ = ( base_events.__all__ + coroutines.__all__ + events.__all__ + futures.__all__ + locks.__all__ + protocols.__all__ + runners.__all__ + queues.__all__ + streams.__all__ + tasks.__all__ )
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/tricky_unicode_symbols.py
tests/data/cases/tricky_unicode_symbols.py
ä = 1 µ = 2 蟒 = 3 x󠄀 = 4 មុ = 1 Q̇_per_meter = 4 A᧚ = 3 A፩ = 8
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/remove_except_types_parens.py
tests/data/cases/remove_except_types_parens.py
# flags: --preview --minimum-version=3.14 # SEE PEP 758 FOR MORE DETAILS # remains unchanged try: pass except: pass # remains unchanged try: pass except ValueError: pass try: pass except* ValueError: pass # parenthesis are removed try: pass except (ValueError): pass try: pass except* (ValueError): pass # parenthesis are removed try: pass except (ValueError) as e: pass try: pass except* (ValueError) as e: pass # remains unchanged try: pass except (ValueError,): pass try: pass except* (ValueError,): pass # remains unchanged try: pass except (ValueError,) as e: pass try: pass except* (ValueError,) as e: pass # remains unchanged try: pass except ValueError, TypeError, KeyboardInterrupt: pass try: pass except* ValueError, TypeError, KeyboardInterrupt: pass # parenthesis are removed try: pass except (ValueError, TypeError, KeyboardInterrupt): pass try: pass except* (ValueError, TypeError, KeyboardInterrupt): pass # parenthesis are not removed try: pass except (ValueError, TypeError, KeyboardInterrupt) as e: pass try: pass except* (ValueError, TypeError, KeyboardInterrupt) as e: pass # parenthesis are removed try: pass except (ValueError if True else TypeError): pass try: pass except* (ValueError if True else TypeError): pass # inner except: parenthesis are removed # outer except: parenthsis are not removed try: try: pass except (TypeError, KeyboardInterrupt): pass except (ValueError,): pass try: try: pass except* (TypeError, KeyboardInterrupt): pass except* (ValueError,): pass # output # SEE PEP 758 FOR MORE DETAILS # remains unchanged try: pass except: pass # remains unchanged try: pass except ValueError: pass try: pass except* ValueError: pass # parenthesis are removed try: pass except ValueError: pass try: pass except* ValueError: pass # parenthesis are removed try: pass except ValueError as e: pass try: pass except* ValueError as e: pass # remains unchanged try: pass except (ValueError,): pass try: pass except* (ValueError,): pass # remains unchanged try: pass except (ValueError,) as e: pass try: pass except* (ValueError,) as e: pass # remains unchanged try: pass except ValueError, TypeError, KeyboardInterrupt: pass try: pass except* ValueError, TypeError, KeyboardInterrupt: pass # parenthesis are removed try: pass except ValueError, TypeError, KeyboardInterrupt: pass try: pass except* ValueError, TypeError, KeyboardInterrupt: pass # parenthesis are not removed try: pass except (ValueError, TypeError, KeyboardInterrupt) as e: pass try: pass except* (ValueError, TypeError, KeyboardInterrupt) as e: pass # parenthesis are removed try: pass except ValueError if True else TypeError: pass try: pass except* ValueError if True else TypeError: pass # inner except: parenthesis are removed # outer except: parenthsis are not removed try: try: pass except TypeError, KeyboardInterrupt: pass except (ValueError,): pass try: try: pass except* TypeError, KeyboardInterrupt: pass except* (ValueError,): pass
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/raw_docstring.py
tests/data/cases/raw_docstring.py
# flags: --skip-string-normalization class C: r"""Raw""" def f(): r"""Raw""" class SingleQuotes: r'''Raw''' class UpperCaseR: R"""Raw""" # output class C: r"""Raw""" def f(): r"""Raw""" class SingleQuotes: r'''Raw''' class UpperCaseR: R"""Raw"""
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/fmtonoff2.py
tests/data/cases/fmtonoff2.py
import pytest TmSt = 1 TmEx = 2 # fmt: off # Test data: # Position, Volume, State, TmSt/TmEx/None, [call, [arg1...]] @pytest.mark.parametrize('test', [ # Test don't manage the volume [ ('stuff', 'in') ], ]) def test_fader(test): pass def check_fader(test): pass def verify_fader(test): # misaligned comment pass def verify_fader(test): """Hey, ho.""" assert test.passed() def test_calculate_fades(): calcs = [ # one is zero/none (0, 4, 0, 0, 10, 0, 0, 6, 10), (None, 4, 0, 0, 10, 0, 0, 6, 10), ] # fmt: on
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/pattern_matching_generic.py
tests/data/cases/pattern_matching_generic.py
# flags: --minimum-version=3.10 re.match() match = a with match() as match: match = f"{match}" re.match() match = a with match() as match: match = f"{match}" def get_grammars(target_versions: Set[TargetVersion]) -> List[Grammar]: if not target_versions: # No target_version specified, so try all grammars. return [ # Python 3.7+ pygram.python_grammar_no_print_statement_no_exec_statement_async_keywords, # Python 3.0-3.6 pygram.python_grammar_no_print_statement_no_exec_statement, # Python 2.7 with future print_function import pygram.python_grammar_no_print_statement, # Python 2.7 pygram.python_grammar, ] match match: case case: match match: case case: pass if all(version.is_python2() for version in target_versions): # Python 2-only code, so try Python 2 grammars. return [ # Python 2.7 with future print_function import pygram.python_grammar_no_print_statement, # Python 2.7 pygram.python_grammar, ] re.match() match = a with match() as match: match = f"{match}" def test_patma_139(self): x = False match x: case bool(z): y = 0 self.assertIs(x, False) self.assertEqual(y, 0) self.assertIs(z, x) # Python 3-compatible code, so only try Python 3 grammar. grammars = [] if supports_feature(target_versions, Feature.PATTERN_MATCHING): # Python 3.10+ grammars.append(pygram.python_grammar_soft_keywords) # If we have to parse both, try to parse async as a keyword first if not supports_feature( target_versions, Feature.ASYNC_IDENTIFIERS ) and not supports_feature(target_versions, Feature.PATTERN_MATCHING): # Python 3.7-3.9 grammars.append( pygram.python_grammar_no_print_statement_no_exec_statement_async_keywords ) if not supports_feature(target_versions, Feature.ASYNC_KEYWORDS): # Python 3.0-3.6 grammars.append(pygram.python_grammar_no_print_statement_no_exec_statement) def test_patma_155(self): x = 0 y = None match x: case 1e1000: y = 0 self.assertEqual(x, 0) self.assertIs(y, None) x = range(3) match x: case [y, case as x, z]: w = 0 # At least one of the above branches must have been taken, because every Python # version has exactly one of the two 'ASYNC_*' flags return grammars def lib2to3_parse(src_txt: str, target_versions: Iterable[TargetVersion] = ()) -> Node: """Given a string with source, return the lib2to3 Node.""" if not src_txt.endswith("\n"): src_txt += "\n" grammars = get_grammars(set(target_versions)) re.match() match = a with match() as match: match = f"{match}" re.match() match = a with match() as match: match = f"{match}"
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/preview_import_line_collapse.py
tests/data/cases/preview_import_line_collapse.py
# flags: --preview from middleman.authentication import validate_oauth_token logger = logging.getLogger(__name__) # case 2 comment after import from middleman.authentication import validate_oauth_token #comment logger = logging.getLogger(__name__) # case 3 comment after import from middleman.authentication import validate_oauth_token # comment logger = logging.getLogger(__name__) from middleman.authentication import validate_oauth_token logger = logging.getLogger(__name__) # case 4 try catch with import after import import os import os try: import os except Exception: pass try: import os def func(): a = 1 except Exception: pass # case 5 multiple imports import os import os import os import os for i in range(10): print(i) # case 6 import in function def func(): print() import os def func(): pass print() def func(): import os a = 1 print() def func(): import os a = 1 print() def func(): import os a = 1 print() # output from middleman.authentication import validate_oauth_token logger = logging.getLogger(__name__) # case 2 comment after import from middleman.authentication import validate_oauth_token # comment logger = logging.getLogger(__name__) # case 3 comment after import from middleman.authentication import validate_oauth_token # comment logger = logging.getLogger(__name__) from middleman.authentication import validate_oauth_token logger = logging.getLogger(__name__) # case 4 try catch with import after import import os import os try: import os except Exception: pass try: import os def func(): a = 1 except Exception: pass # case 5 multiple imports import os import os import os import os for i in range(10): print(i) # case 6 import in function def func(): print() import os def func(): pass print() def func(): import os a = 1 print() def func(): import os a = 1 print() def func(): import os a = 1 print()
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/preview_long_strings__east_asian_width.py
tests/data/cases/preview_long_strings__east_asian_width.py
# flags: --unstable # The following strings do not have not-so-many chars, but are long enough # when these are rendered in a monospace font (if the renderer respects # Unicode East Asian Width properties). hangul = '코드포인트 수는 적으나 실제 터미널이나 에디터에서 렌더링될 땐 너무 길어서 줄바꿈이 필요한 문자열' hanzi = '中文測試:代碼點數量少,但在真正的終端模擬器或編輯器中呈現時太長,因此需要換行的字符串。' japanese = 'コードポイントの数は少ないが、実際の端末エミュレータやエディタでレンダリングされる時は長すぎる為、改行が要る文字列' # output # The following strings do not have not-so-many chars, but are long enough # when these are rendered in a monospace font (if the renderer respects # Unicode East Asian Width properties). hangul = ( "코드포인트 수는 적으나 실제 터미널이나 에디터에서 렌더링될 땐 너무 길어서 줄바꿈이" " 필요한 문자열" ) hanzi = ( "中文測試:代碼點數量少,但在真正的終端模擬器或編輯器中呈現時太長," "因此需要換行的字符串。" ) japanese = ( "コードポイントの数は少ないが、" "実際の端末エミュレータやエディタでレンダリングされる時は長すぎる為、" "改行が要る文字列" )
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/python38.py
tests/data/cases/python38.py
def starred_return(): my_list = ["value2", "value3"] return "value1", *my_list def starred_yield(): my_list = ["value2", "value3"] yield "value1", *my_list # all right hand side expressions allowed in regular assignments are now also allowed in # annotated assignments a : Tuple[ str, int] = "1", 2 a: Tuple[int , ... ] = b, *c, d def t(): a : str = yield "a" # output def starred_return(): my_list = ["value2", "value3"] return "value1", *my_list def starred_yield(): my_list = ["value2", "value3"] yield "value1", *my_list # all right hand side expressions allowed in regular assignments are now also allowed in # annotated assignments a: Tuple[str, int] = "1", 2 a: Tuple[int, ...] = b, *c, d def t(): a: str = yield "a"
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false
psf/black
https://github.com/psf/black/blob/c3cc5a95d4f72e6ccc27ebae23344fce8cc70786/tests/data/cases/trailing_comma_optional_parens2.py
tests/data/cases/trailing_comma_optional_parens2.py
if (e123456.get_tk_patchlevel() >= (8, 6, 0, 'final') or (8, 5, 8) <= get_tk_patchlevel() < (8, 6)): pass # output if e123456.get_tk_patchlevel() >= (8, 6, 0, "final") or ( 8, 5, 8, ) <= get_tk_patchlevel() < (8, 6): pass
python
MIT
c3cc5a95d4f72e6ccc27ebae23344fce8cc70786
2026-01-04T14:40:23.735327Z
false