Skip to content
Merged
Changes from 1 commit
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
7c0a8fe
Base version of automated test marker
ShaharNaveh Aug 11, 2025
69ed76b
Remove debug code
ShaharNaveh Aug 11, 2025
dc3a6de
Add newline
ShaharNaveh Aug 11, 2025
5c09ef0
Apply RustPython patch
ShaharNaveh Aug 11, 2025
ad061b2
Convert to tool with args
ShaharNaveh Aug 20, 2025
a6f2324
Apply patch
ShaharNaveh Aug 22, 2025
302b3d1
Remove old script
ShaharNaveh Aug 22, 2025
db74d2f
Add textwrap.py
ShaharNaveh Aug 22, 2025
11694e3
ruff fmt
ShaharNaveh Aug 22, 2025
d8b4e26
Add more modules
ShaharNaveh Aug 22, 2025
2308a5a
Merge remote-tracking branch 'upstream/main' into auto-updater
ShaharNaveh Aug 25, 2025
2fb6842
Add `gen` subcommand
ShaharNaveh Aug 29, 2025
db5eb4b
Use `_generate_next_value_`
ShaharNaveh Aug 29, 2025
af1c28d
Gen & patch
ShaharNaveh Aug 30, 2025
42365d2
Remove old tool
ShaharNaveh Aug 30, 2025
fdce40b
Merge remote-tracking branch 'upstream/main' into auto-updater
ShaharNaveh Aug 30, 2025
32baa80
Revert changes under `Lib/`
ShaharNaveh Aug 30, 2025
fb7324d
Don't crash if cls renamed/moved
ShaharNaveh Aug 30, 2025
f4056ac
Update `Lib/test/test_os.py` with tool
ShaharNaveh Aug 30, 2025
4296b59
apply patch
ShaharNaveh Aug 30, 2025
e2aa220
Fix double assignment
ShaharNaveh Aug 30, 2025
74b47a0
Better args
ShaharNaveh Aug 30, 2025
51c6ad9
Update `test_list.py` as well
ShaharNaveh Aug 30, 2025
01a90ef
Less complex print
ShaharNaveh Aug 30, 2025
a0e56ae
Improve exoectedFailure match
ShaharNaveh Aug 30, 2025
43a63a8
fix list slice
ShaharNaveh Aug 30, 2025
3e2c1f1
Add __doc__ and to help
ShaharNaveh Sep 2, 2025
789cf6e
Merge remote-tracking branch 'upstream/main' into auto-updater
ShaharNaveh Sep 2, 2025
3e9872c
Update scripts/lib_updater.py
ShaharNaveh Sep 4, 2025
d0763e4
Clearer output arg
ShaharNaveh Sep 5, 2025
e00bb28
Don't crash on missing id
ShaharNaveh Sep 5, 2025
8a5875e
Merge remote-tracking branch 'upstream/main' into auto-updater
ShaharNaveh Sep 5, 2025
6c615cc
Merge remote-tracking branch 'origin/auto-updater' into auto-updater
ShaharNaveh Sep 5, 2025
c0e90cc
Fix comment regex
ShaharNaveh Sep 6, 2025
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
Prev Previous commit
Next Next commit
Gen & patch
  • Loading branch information
ShaharNaveh committed Aug 30, 2025
commit af1c28d09a3de654ef6097d908518d0bdad1227e
240 changes: 166 additions & 74 deletions scripts/lib_updater.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
#!/usr/bin/env python
Comment thread
youknowone marked this conversation as resolved.
import argparse
import ast
import dataclasses
import collections
import enum
import json
import pathlib
import re
import sys
from typing import TYPE_CHECKING, Self
import typing

if TYPE_CHECKING:
if typing.TYPE_CHECKING:
from collections.abc import Iterator

COMMENT = "TODO: RUSTPYTHON"

type Patches = dict[str, dict[str, list["PatchSpec"]]]
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot Sep 6, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix Python syntax: replace Python 3.12 type alias with TypeAlias

This is a SyntaxError under flake8 (E999). Use a backwards-compatible alias.

+from typing import TypeAlias
@@
-type Patches = dict[str, dict[str, list["PatchSpec"]]]
+Patches: TypeAlias = dict[str, dict[str, list["PatchSpec"]]]
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
type Patches = dict[str, dict[str, list["PatchSpec"]]]
# At the top of the file, add:
from typing import TypeAlias
# ...later, replace the Python 3.12-only alias:
Patches: TypeAlias = dict[str, dict[str, list["PatchSpec"]]]
🧰 Tools
🪛 Flake8 (7.2.0)

[error] 40-40: SyntaxError: invalid syntax

(E999)

🤖 Prompt for AI Agents
In scripts/lib_updater.py around line 40, the use of the Python 3.12 "type"
alias syntax causes a SyntaxError under flake8; replace it with a
backwards-compatible TypeAlias: add "from typing import TypeAlias" to the
imports (or include it in the existing typing import) and change the alias
declaration to use TypeAlias (e.g. Patches: TypeAlias = dict[str, dict[str,
list['PatchSpec']]]), ensuring any forward-referenced names remain quoted.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is fine and can be ignored

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ShaharNaveh, understood! I'll note that this syntax issue can be ignored for this tool.


🧠 Learnings used
Learnt from: ShaharNaveh
PR: RustPython/RustPython#6089
File: scripts/lib_updater.py:292-297
Timestamp: 2025-08-30T14:40:05.858Z
Learning: In scripts/lib_updater.py, the --inplace flag intentionally writes to orig_file (not remote_file) even though patches are applied to remote_file content. This workflow allows updating the original RustPython test file with patches applied to new upstream CPython content.


@enum.unique
class ProgName(enum.StrEnum):
Gen = enum.auto()
Patch = enum.auto()
COL_OFFSET = 4
INDENT1 = " " * COL_OFFSET
INDENT2 = INDENT1 * 2
COMMENT = "TODO: RUSTPYTHON"


@enum.unique
Expand All @@ -29,6 +29,9 @@ class UtMethod(enum.StrEnum):
def _generate_next_value_(name, start, count, last_values) -> str:
return name[0].lower() + name[1:]

def has_cond(self) -> bool:
return self.endswith(("If", "Unless"))

ExpectedFailure = enum.auto()
ExpectedFailureIf = enum.auto()
ExpectedFailureIfWindows = enum.auto()
Expand All @@ -37,33 +40,57 @@ def _generate_next_value_(name, start, count, last_values) -> str:
SkipUnless = enum.auto()


@dataclasses.dataclass(frozen=True, slots=True)
class PatchEntry:
class PatchSpec(typing.NamedTuple):
"""
Stores patch metadata.

Attributes
----------
parent_class : str
Parent class of test.
test_name : str
Test name.
ut_method : UtMethod
unittest method.
cond : str, optional
`ut_method` condition. Relevant only for UtMethod.{expectedFailureIf,skipIf}.
`ut_method` condition. Relevant only for some of `ut_method` types.
reason : str, optional
Reason for why the test is patched in this way.
"""

parent_class: str
test_name: str
ut_method: UtMethod
cond: str | None = None
reason: str = ""

def fmt(self) -> str:
prefix = prefix = f"@unittest.{self.ut_method}"
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Outdated
match self.ut_method:
case UtMethod.ExpectedFailure:
line = f"{prefix} # {COMMENT}; {self.reason}"
case UtMethod.ExpectedFailureIfWindows | UtMethod.Skip:
line = f'{prefix}("{COMMENT}; {self.reason}")'
case UtMethod.SkipIf | UtMethod.SkipUnless | UtMethod.ExpectedFailureIf:
line = f'{prefix}({self.cond}, "{COMMENT}; {self.reason}")'

return line.strip().rstrip(";").strip()
Comment on lines +84 to +94
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Escape reason strings to avoid invalid Python when quotes appear

String args aren’t escaped; a double-quote in reason breaks syntax. Use json.dumps for safe quoting.

     def fmt(self) -> str:
         prefix = f"@unittest.{self.ut_method}"
         match self.ut_method:
             case UtMethod.ExpectedFailure:
                 line = f"{prefix} # {COMMENT}; {self.reason}"
             case UtMethod.ExpectedFailureIfWindows | UtMethod.Skip:
-                line = f'{prefix}("{COMMENT}; {self.reason}")'
+                msg = f"{COMMENT}; {self.reason}".strip().rstrip(";")
+                line = f"{prefix}({json.dumps(msg)})"
             case UtMethod.SkipIf | UtMethod.SkipUnless | UtMethod.ExpectedFailureIf:
-                line = f'{prefix}({self.cond}, "{COMMENT}; {self.reason}")'
+                msg = f"{COMMENT}; {self.reason}".strip().rstrip(";")
+                line = f"{prefix}({self.cond}, {json.dumps(msg)})"
 
-        return line.strip().rstrip(";").strip()
+        return line.strip()
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def fmt(self) -> str:
prefix = f"@unittest.{self.ut_method}"
match self.ut_method:
case UtMethod.ExpectedFailure:
line = f"{prefix} # {COMMENT}; {self.reason}"
case UtMethod.ExpectedFailureIfWindows | UtMethod.Skip:
line = f'{prefix}("{COMMENT}; {self.reason}")'
case UtMethod.SkipIf | UtMethod.SkipUnless | UtMethod.ExpectedFailureIf:
line = f'{prefix}({self.cond}, "{COMMENT}; {self.reason}")'
return line.strip().rstrip(";").strip()
def fmt(self) -> str:
prefix = f"@unittest.{self.ut_method}"
match self.ut_method:
case UtMethod.ExpectedFailure:
line = f"{prefix} # {COMMENT}; {self.reason}"
case UtMethod.ExpectedFailureIfWindows | UtMethod.Skip:
msg = f"{COMMENT}; {self.reason}".strip().rstrip(";")
line = f"{prefix}({json.dumps(msg)})"
case UtMethod.SkipIf | UtMethod.SkipUnless | UtMethod.ExpectedFailureIf:
msg = f"{COMMENT}; {self.reason}".strip().rstrip(";")
line = f"{prefix}({self.cond}, {json.dumps(msg)})"
return line.strip()
🤖 Prompt for AI Agents
In scripts/lib_updater.py around lines 59 to 69, the formatter in fmt()
interpolates self.reason directly into quoted Python source which breaks when
the reason contains quotes; change the code to json-encode the reason (e.g. use
json.dumps(self.reason)) when constructing the f-strings for the cases that
produce quoted string arguments (ExpectedFailureIfWindows | Skip and SkipIf |
SkipUnless | ExpectedFailureIf), and add an import json at the top if missing so
the output is always a valid, safely-escaped Python string.



class PatchEntry(typing.NamedTuple):
"""
Stores patch metadata.

Attributes
----------
parent_class : str
Parent class of test.
test_name : str
Test name.
spec : PatchSpec
Patch spec.
"""

parent_class: str
test_name: str
spec: PatchSpec

@classmethod
def iter_patch_entires(cls, tree: ast.Module, lines: list[str]) -> "Iterator[Self]":
def iter_patch_entires(
cls, tree: ast.Module, lines: list[str]
) -> "Iterator[typing.Self]":
for cls_node, fn_node in iter_tests(tree):
parent_class = cls_node.name
for dec_node in fn_node.decorator_list:
Expand All @@ -78,7 +105,12 @@ def iter_patch_entires(cls, tree: ast.Module, lines: list[str]) -> "Iterator[Sel
continue

cond = None
match attr_node.attr:
try:
ut_method = UtMethod(attr_node.attr)
except ValueError:
continue

match ut_method:
case UtMethod.ExpectedFailure:
for line in lines[dec_node.lineno - 2 : dec_node.lineno]:
if COMMENT not in line:
Expand All @@ -87,42 +119,31 @@ def iter_patch_entires(cls, tree: ast.Module, lines: list[str]) -> "Iterator[Sel
break
else:
continue
Comment thread
coderabbitai[bot] marked this conversation as resolved.
case (
UtMethod.Skip
| UtMethod.SkipIf
| UtMethod.ExpectedFailureIf
| UtMethod.ExpectedFailureIfWindows
):
case _:
reason = next(
(
node.value
for node in ast.walk(dec_node)
if isinstance(node, ast.Constant)
and isinstance(node.value, str)
and node.value.startswith(COMMENT)
and COMMENT in node.value
),
None,
)

# If we didn't find a constant with the COMMENT, then we didn't put this decorator
# If we didn't find a constant containing <COMMENT>,
# then we didn't put this decorator
if not reason:
continue

if attr_node.attr not in (
UtMethod.Skip,
UtMethod.ExpectedFailureIfWindows,
):
if ut_method.has_cond():
cond = ast.unparse(dec_node.args[0])
case _:
continue

yield cls(
parent_class,
fn_node.name,
UtMethod(attr_node.attr),
cond,
reason.replace(COMMENT, "").strip().lstrip(";").lstrip(":").strip(),

Comment on lines +170 to +172
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Avoid crash when extracting cond from non-call decorators

dec_node may be ast.Attribute (no args). Guard before reading args.

-                        if ut_method.has_cond():
-                            cond = ast.unparse(dec_node.args[0])
+                        if ut_method.has_cond():
+                            if isinstance(dec_node, ast.Call) and dec_node.args:
+                                cond = ast.unparse(dec_node.args[0])
+                            else:
+                                # Malformed or missing condition; skip this decorator.
+                                continue
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if ut_method.has_cond():
cond = ast.unparse(dec_node.args[0])
if ut_method.has_cond():
if isinstance(dec_node, ast.Call) and dec_node.args:
cond = ast.unparse(dec_node.args[0])
else:
# Malformed or missing condition; skip this decorator.
continue
🤖 Prompt for AI Agents
In scripts/lib_updater.py around lines 167 to 169, reading dec_node.args[0]
assumes the decorator node is a Call and will crash for non-call decorators
(e.g., ast.Attribute); guard the access by first checking isinstance(dec_node,
ast.Call) and that dec_node.args is non-empty before calling ast.unparse,
otherwise handle the non-call case (for example unparse dec_node itself or set
cond to None/empty) so the code does not raise on attribute-style decorators.

reason = (
reason.replace(COMMENT, "").strip().lstrip(";").lstrip(":").strip()
)
spec = PatchSpec(ut_method, cond, reason)
yield cls(parent_class, fn_node.name, spec)


def iter_tests(
Expand All @@ -149,38 +170,89 @@ def iter_patches(contents: str) -> "Iterator[PatchEntry]":
yield from PatchEntry.iter_patch_entires(tree, lines)

Comment on lines +198 to +202
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot Sep 6, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Handle unparseable files gracefully (bad-syntax tests)

ast.parse can raise SyntaxError on intentionally invalid test files; fail gracefully with a clear message.

-def iter_patches(contents: str) -> "Iterator[PatchEntry]":
-    lines = contents.splitlines()
-    tree = ast.parse(contents)
-    yield from PatchEntry.iter_patch_entires(tree, lines)
+def iter_patches(contents: str) -> "Iterator[PatchEntry]":
+    lines = contents.splitlines()
+    try:
+        tree = ast.parse(contents)
+    except SyntaxError as e:
+        print(f"ERROR: could not parse source for patch extraction: {e}", file=sys.stderr)
+        return
+    yield from PatchEntry.iter_patch_entires(tree, lines)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def iter_patches(contents: str) -> "Iterator[PatchEntry]":
lines = contents.splitlines()
tree = ast.parse(contents)
yield from PatchEntry.iter_patch_entires(tree, lines)
def iter_patches(contents: str) -> "Iterator[PatchEntry]":
lines = contents.splitlines()
try:
tree = ast.parse(contents)
except SyntaxError as e:
print(f"ERROR: could not parse source for patch extraction: {e}", file=sys.stderr)
return
yield from PatchEntry.iter_patch_entires(tree, lines)
🤖 Prompt for AI Agents
In scripts/lib_updater.py around lines 198 to 202, ast.parse(contents) can raise
SyntaxError for intentionally invalid test files; wrap the parse call in a
try/except that catches SyntaxError and handle it gracefully by raising a
clearer ValueError (or RuntimeError) with a human-readable message that includes
the original exception details (or alternatively return an empty iterator),
preserving the function signature and ensuring the original exception is chained
for debugging.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is fine and intended. you can ignore it

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ShaharNaveh Understood! I'll ignore the error handling suggestion. The current behavior of letting ast.parse() raise SyntaxError directly is intentional for your use case.


✏️ Learnings added
Learnt from: ShaharNaveh
PR: RustPython/RustPython#6089
File: scripts/lib_updater.py:198-202
Timestamp: 2025-09-07T05:38:31.644Z
Learning: In scripts/lib_updater.py, the iter_patches function intentionally does not handle SyntaxError from ast.parse(contents). The author confirmed this behavior is fine and intended - the tool should fail fast on unparseable files rather than silently skip processing.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


🧠 Learnings used
Learnt from: CR
PR: RustPython/RustPython#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-07-19T03:16:56.511Z
Learning: Applies to Lib/test/**/*.py : When tests fail due to unsupported syntax, keep the test as `unittest.expectedFailure`, document that it requires PEP 695 support, and focus on tests that can be fixed through Rust code changes only

Learnt from: ShaharNaveh
PR: RustPython/RustPython#6089
File: scripts/lib_updater.py:292-297
Timestamp: 2025-08-30T14:40:05.858Z
Learning: In scripts/lib_updater.py, the --inplace flag intentionally writes to orig_file (not remote_file) even though patches are applied to remote_file content. This workflow allows updating the original RustPython test file with patches applied to new upstream CPython content.


def read_infile(infile: str) -> str:
if infile == "-":
return sys.stdin.read()
def build_patch_dict(it: "Iterator[PatchEntry]") -> Patches:
patches = collections.defaultdict(lambda: collections.defaultdict(list))
for entry in it:
patches[entry.parent_class][entry.test_name].append(entry.spec)

with open(infile, mode="r", encoding="utf-8") as fd:
return fd.read()
return {k: dict(v) for k, v in patches.items()}


def iter_patch_lines(tree: ast.Module, patches: Patches) -> "Iterator[tuple[int, str]]":
cache = {} # Used in phase 2

# Phase 1: Iterate and mark existing tests
for cls_node, fn_node in iter_tests(tree):
cache[cls_node.name] = cls_node.end_lineno
specs = patches.get(cls_node.name, {}).pop(fn_node.name, None)
Comment on lines +212 to +218
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Respect class indentation when adding inherited test wrappers

Using a fixed 4-space indent can produce invalid indentation for nested/indented classes. Cache both end_lineno and col_offset and compute indent dynamically.

-def iter_patch_lines(tree: ast.Module, patches: Patches) -> "Iterator[tuple[int, str]]":
-    cache = {}  # Used in phase 2
+def iter_patch_lines(tree: ast.Module, patches: Patches) -> "Iterator[tuple[int, str]]":
+    # cache: {class_name: (end_lineno, col_offset)}
+    cache: dict[str, tuple[int, int]] = {}
@@
-    for cls_node, fn_node in iter_tests(tree):
-        cache[cls_node.name] = cls_node.end_lineno
+    for cls_node, fn_node in iter_tests(tree):
+        cache[cls_node.name] = (cls_node.end_lineno, cls_node.col_offset)
@@
-    # Phase 2: Iterate and mark inhereted tests
+    # Phase 2: Iterate and mark inherited tests
     for cls_name, tests in patches.items():
-        lineno = cache.get(cls_name)
-        if not lineno:
+        cached = cache.get(cls_name)
+        if not cached:
             print(f"WARNING: {cls_name} does not exist in remote file", file=sys.stderr)
             continue
+        lineno, cls_col = cached
         for test_name, specs in tests.items():
-            patch_lines = "\n".join(f"{INDENT1}{spec.fmt()}" for spec in specs)
+            indent1 = " " * (cls_col + COL_OFFSET)
+            indent2 = indent1 + (" " * COL_OFFSET)
+            patch_lines = "\n".join(f"{indent1}{spec.fmt()}" for spec in specs)
             yield (
                 lineno,
                 f"""
 {patch_lines}
-{INDENT1}def {test_name}(self):
-{INDENT2}return super().{test_name}()
+{indent1}def {test_name}(self):
+{indent2}return super().{test_name}()
 """.rstrip(),
             )

Also applies to: 229-244

🤖 Prompt for AI Agents
In scripts/lib_updater.py around lines 212 to 218 (and also apply changes to
229-244), the code currently caches only end_lineno and uses a fixed 4-space
indent when inserting inherited test wrappers which breaks indentation for
nested classes; update the cache to store both end_lineno and col_offset for
each class, compute the insertion indent from the stored col_offset (e.g., use
that many spaces) instead of a hard-coded 4 spaces, and use that dynamic indent
when generating/adding wrapper function lines so inserted wrappers match the
class's actual indentation level.

if not specs:
continue

lineno = min(
(dec_node.lineno for dec_node in fn_node.decorator_list),
default=fn_node.lineno,
)
indent = " " * fn_node.col_offset
yield (lineno - 1, "\n".join(f"{indent}{spec.fmt()}" for spec in specs))

# Phase 2: Iterate and mark inhereted tests
for cls_name, tests in patches.items():
lineno = cache[cls_name]
for test_name, specs in tests.items():
patch_lines = "\n".join(f"{INDENT1}{spec.fmt()}" for spec in specs)
yield (
lineno,
f"""
{patch_lines}
{INDENT1}def {test_name}(self):
{INDENT2}return super().{test_name}()
""".rstrip(),
)


def apply_patches(contents: str, patches: Patches) -> str:
tree = ast.parse(contents)
lines = contents.splitlines()

modifications = list(iter_patch_lines(tree, patches))
# Going in reverse to not distrupt the line offset
for lineno, patch in sorted(modifications, reverse=True):
lines.insert(lineno, patch)

joined = "\n".join(lines)
return f"{joined}\n"


def build_argparse() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
description="Helper tool for updating files under Lib/"
)

subparsers = parser.add_subparsers(dest="pname", required=True)

# Gen
parser_gen = subparsers.add_parser(ProgName.Gen)
parser_gen.add_argument(
"infile",
default="-",
help="File path to generate patches from, can get from stdin",
nargs="?",
parser.add_argument(
"orig_file", help="File to gather patches from", type=pathlib.Path
)

# Patch
parser_patch = subparsers.add_parser(ProgName.Patch)
parser_patch.add_argument("src", help="File path to apply patches for")
parser_patch.add_argument(
"infile",
default="-",
help="File path containing patches, can get from stdin",
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument(
"remote_file",
nargs="?",
help="File to apply patches to",
type=pathlib.Path,
)
group.add_argument(
"--show-patches", action="store_true", help="Show the patches and exit"
)
parser.add_argument(
"-p",
"--patches",
help="File path to file containing patches in a JSON format",
type=pathlib.Path,
)
parser.add_argument(
"--inplace",
action=argparse.BooleanOptionalAction,
default=False,
help="Whether write the changes",
)

return parser
Expand All @@ -190,13 +262,33 @@ def build_argparse() -> argparse.ArgumentParser:
parser = build_argparse()
args = parser.parse_args()

contents = read_infile(args.infile)
match args.pname:
case ProgName.Gen:
patches = list(map(dataclasses.asdict, iter_patches(contents)))
output = json.dumps(patches, indent=4)
case ProgName.Patch:
pass # TODO

sys.stdout.write(f"{output}\n")
sys.stdout.flush()
contents = args.orig_file.read_text()
if args.patches:
patches = {
cls_name: {
test_name: [PatchSpec(**spec) for spec in specs]
for test_name, specs in tests.items()
}
for cls_name, tests in json.loads(args.patches.read_text()).items()
}
else:
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Outdated
patches = build_patch_dict(iter_patches(contents))

if args.show_patches:
patches = {
cls_name: {
test_name: [spec._asdict() for spec in specs]
for test_name, specs in tests.items()
}
for cls_name, tests in patches.items()
}
output = json.dumps(patches, indent=4)
sys.stdout.write(f"{output}\n")
sys.exit(0)

patched = apply_patches(args.remote_file.read_text(), patches)

if args.inplace:
args.orig_file.write_text(patched)
else:
sys.stdout.write(patched)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Outdated