diff --git a/src/poetry_plugin_export/command.py b/src/poetry_plugin_export/command.py index 06ca162..87b6063 100644 --- a/src/poetry_plugin_export/command.py +++ b/src/poetry_plugin_export/command.py @@ -51,6 +51,11 @@ class ExportCommand(GroupCommand): ), option("all-extras", None, "Include all sets of extra dependencies."), option("with-credentials", None, "Include credentials for extra indices."), + option( + "check-change", + None, + "Return code 1 if file changed. Useful for pre-commit.", + ), ] @property @@ -101,6 +106,15 @@ def handle(self) -> int: ) return 1 + check_change = self.option("check-change") + if check_change and not output: + self.line_error( + "You must specify" + " `--output` if" + " using `--check-change`." + ) + return 1 + extras: Iterable[NormalizedName] if self.option("all-extras"): extras = self.poetry.package.extras.keys() @@ -122,6 +136,10 @@ def handle(self) -> int: exporter.with_hashes(not self.option("without-hashes")) exporter.with_credentials(self.option("with-credentials")) exporter.with_urls(not self.option("without-urls")) - exporter.export(fmt, Path.cwd(), output or self.io) - return 0 + if check_change: + changed = exporter.export_and_check_change(fmt, Path.cwd(), output) + return 1 if changed else 0 + else: + exporter.export(fmt, Path.cwd(), output or self.io) + return 0 diff --git a/src/poetry_plugin_export/exporter.py b/src/poetry_plugin_export/exporter.py index 167980e..d122e1f 100644 --- a/src/poetry_plugin_export/exporter.py +++ b/src/poetry_plugin_export/exporter.py @@ -3,6 +3,7 @@ import urllib.parse from functools import partialmethod +from pathlib import Path from typing import TYPE_CHECKING from typing import Iterable @@ -15,7 +16,6 @@ if TYPE_CHECKING: from collections.abc import Collection - from pathlib import Path from typing import ClassVar from packaging.utils import NormalizedName @@ -80,6 +80,14 @@ def export(self, fmt: str, cwd: Path, output: IO | str) -> None: getattr(self, self.EXPORT_METHODS[fmt])(cwd, output) + def export_and_check_change(self, fmt: str, cwd: Path, output: str) -> bool: + output_path = Path(output) + orig_content = output_path.read_bytes() if output_path.exists() else None + self.export(fmt, cwd, output) + new_content = output_path.read_bytes() + changed = new_content != orig_content + return changed + def _export_generic_txt( self, cwd: Path, output: IO | str, with_extras: bool, allow_editable: bool ) -> None: