Skip to content

Apply changes only if text actually changed #15

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

Merged
merged 1 commit into from
Jun 28, 2024
Merged
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
25 changes: 17 additions & 8 deletions auto_typing_final/transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,27 +86,33 @@ def make_operation_from_assignments_to_one_name(nodes: list[SgNode]) -> Operatio
return RemoveFinal(assignments)


def make_edits_from_operation(operation: Operation) -> Iterable[Edit]: # noqa: C901
def make_expected_text_from_operation(operation: Operation) -> Iterable[tuple[SgNode, str]]: # noqa: C901
match operation:
case AddFinal(assignment):
match assignment:
case AssignmentWithoutAnnotation(node, left, right):
yield node.replace(f"{left}: {TYPING_FINAL} = {right}")
yield node, f"{left}: {TYPING_FINAL} = {right}"
case AssignmentWithAnnotation(node, left, annotation, right):
if TYPING_FINAL in annotation:
return
yield node.replace(f"{left}: {TYPING_FINAL}[{annotation}] = {right}")
yield node, f"{left}: {TYPING_FINAL}[{annotation}] = {right}"

case RemoveFinal(assignments):
for assignment in assignments:
match assignment:
case AssignmentWithoutAnnotation(node, left, right):
yield node.replace(f"{left} = {right}")
yield node, f"{left} = {right}"
case AssignmentWithAnnotation(node, left, annotation, right):
if annotation == TYPING_FINAL:
yield node.replace(f"{left} = {right}")
yield node, f"{left} = {right}"
elif new_annotation := TYPING_FINAL_ANNOTATION_REGEX.findall(annotation):
yield node.replace(f"{left}: {new_annotation[0]} = {right}")
yield node, f"{left}: {new_annotation[0]} = {right}"


def make_edits_from_operation(operation: Operation) -> Iterable[Edit]:
for node, new_text in make_expected_text_from_operation(operation):
if node.text() != new_text:
yield node.replace(new_text)


def make_edits_for_module(root: SgNode) -> str:
Expand All @@ -115,9 +121,12 @@ def make_edits_for_module(root: SgNode) -> str:

for current_definitions in find_definitions_in_module(root):
operation = make_operation_from_assignments_to_one_name(current_definitions)
if isinstance(operation, AddFinal):
current_edits = list(make_edits_from_operation(operation))

if isinstance(operation, AddFinal) and current_edits:
has_added_final = True
edits.extend(make_edits_from_operation(operation))

edits.extend(current_edits)

result = root.commit_edits(edits)

Expand Down