Skip to content

Update change.py #86

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 33 additions & 5 deletions refactor/change.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import difflib
import os
import argparse
from dataclasses import dataclass
from pathlib import Path

Expand Down Expand Up @@ -40,16 +41,43 @@ def compute_diff(self) -> str:
)
)

def apply_diff(self) -> None:
def apply_diff(self, dry_run: bool = False) -> None:
"""Apply the transformed version to the bound file."""
raw_source = self.refactored_source.encode(self.file_info.get_encoding())

with open(self.file, "wb") as stream:
stream.write(raw_source)
if dry_run:
diff = self.compute_diff()
print(diff)
else:
raw_source = self.refactored_source.encode(self.file_info.get_encoding())
with open(self.file, "wb") as stream:
stream.write(raw_source)

@property
def file(self) -> Path:
"""Returns the bound file."""
if self.file_info.path is None:
raise ValueError("Change expects a valid file")
return self.file_info.path


def refactor_file(file_path, dry_run=False):
# Perform the refactoring logic here and get the refactored_source
original_source = open(file_path).read()
# Assume refactored_source is obtained somehow in the refactoring process

change = Change(file_info=_FileInfo(path=Path(file_path)), original_source=original_source, refactored_source=refactored_source)
change.apply_diff(dry_run=dry_run)


if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Refactor code.")
parser.add_argument("file_path", help="Path to the file to be refactored.")
parser.add_argument("--diff", action="store_true", help="Perform a dry-run and show the diff.")
parser.add_argument("--fail-on-change", action="store_true", help="Exit with 1 if there are any changes without refactoring.")

args = parser.parse_args()

refactor_file(args.file_path, dry_run=args.diff)

if args.fail_on_change and args.diff:
print("Exiting with code 1 due to changes without refactoring.")
exit(1)