tass 0.1.2__py3-none-any.whl → 0.1.4__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- src/app.py +52 -27
- src/constants.py +14 -12
- {tass-0.1.2.dist-info → tass-0.1.4.dist-info}/METADATA +1 -1
- tass-0.1.4.dist-info/RECORD +10 -0
- src/third_party/README.md +0 -1
- src/third_party/__init__.py +0 -0
- src/third_party/apply_patch.md +0 -64
- src/third_party/apply_patch.py +0 -529
- tass-0.1.2.dist-info/RECORD +0 -14
- {tass-0.1.2.dist-info → tass-0.1.4.dist-info}/WHEEL +0 -0
- {tass-0.1.2.dist-info → tass-0.1.4.dist-info}/entry_points.txt +0 -0
- {tass-0.1.2.dist-info → tass-0.1.4.dist-info}/licenses/LICENSE +0 -0
src/app.py
CHANGED
|
@@ -10,7 +10,6 @@ from src.constants import (
|
|
|
10
10
|
SYSTEM_PROMPT,
|
|
11
11
|
TOOLS,
|
|
12
12
|
)
|
|
13
|
-
from src.third_party.apply_patch import apply_patch
|
|
14
13
|
from src.utils import (
|
|
15
14
|
is_read_only_command,
|
|
16
15
|
)
|
|
@@ -25,8 +24,8 @@ class TassApp:
|
|
|
25
24
|
self.host = os.environ.get("TASS_HOST", "http://localhost:8080")
|
|
26
25
|
self.TOOLS_MAP = {
|
|
27
26
|
"execute": self.execute,
|
|
28
|
-
"apply_patch": self.apply_patch_tass,
|
|
29
27
|
"read_file": self.read_file,
|
|
28
|
+
"edit_file": self.edit_file,
|
|
30
29
|
}
|
|
31
30
|
|
|
32
31
|
def _check_llm_host(self):
|
|
@@ -127,44 +126,62 @@ class TassApp:
|
|
|
127
126
|
def read_file(self, path: str, start: int = 1) -> str:
|
|
128
127
|
console.print(f" └ Reading file [bold]{path}[/]...")
|
|
129
128
|
|
|
129
|
+
try:
|
|
130
|
+
with open(path) as f:
|
|
131
|
+
out = f.read()
|
|
132
|
+
except Exception as e:
|
|
133
|
+
console.print(" [red]read_file failed[/red]")
|
|
134
|
+
console.print(f" [red]{str(e)}[/red]")
|
|
135
|
+
return f"read_file failed: {str(e)}"
|
|
136
|
+
|
|
130
137
|
lines = []
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
if line_num < start:
|
|
135
|
-
line_num += 1
|
|
136
|
-
continue
|
|
137
|
-
|
|
138
|
-
lines.append(line)
|
|
138
|
+
line_num = 1
|
|
139
|
+
for line in out.split("\n"):
|
|
140
|
+
if line_num < start:
|
|
139
141
|
line_num += 1
|
|
142
|
+
continue
|
|
140
143
|
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
+
lines.append(line)
|
|
145
|
+
line_num += 1
|
|
146
|
+
|
|
147
|
+
if len(lines) >= 1000:
|
|
148
|
+
lines.append("... (truncated)")
|
|
149
|
+
break
|
|
144
150
|
|
|
145
151
|
console.print(" [green]Command succeeded[/green]")
|
|
146
152
|
return "".join(lines)
|
|
147
153
|
|
|
148
|
-
def
|
|
154
|
+
def edit_file(self, path: str, find: str, replace: str) -> str:
|
|
155
|
+
find_with_minuses = "\n".join([f"-{line}" for line in find.split("\n")])
|
|
156
|
+
replace_with_pluses = "\n".join([f"+{line}" for line in replace.split("\n")])
|
|
149
157
|
console.print()
|
|
150
|
-
console.print(Markdown(f"```diff\n{
|
|
158
|
+
console.print(Markdown(f"```diff\nEditing {path}\n{find_with_minuses}\n{replace_with_pluses}\n```"))
|
|
151
159
|
answer = console.input("\n[bold]Run?[/] ([bold]Y[/]/n): ").strip().lower()
|
|
152
160
|
if answer not in ("yes", "y", ""):
|
|
153
161
|
reason = console.input("Why not? (optional, press Enter to skip): ").strip()
|
|
154
162
|
return f"User declined: {reason or 'no reason'}"
|
|
155
163
|
|
|
156
164
|
console.print(" └ Running...")
|
|
157
|
-
|
|
158
165
|
try:
|
|
159
|
-
|
|
166
|
+
with open(path, "r") as f:
|
|
167
|
+
original_content = f.read()
|
|
168
|
+
|
|
169
|
+
if find not in original_content:
|
|
170
|
+
console.print(" [red]edit_file failed[/red]")
|
|
171
|
+
console.print(f" [red]edit_file failed:\n'{find}'\nnot found in file[/red]")
|
|
172
|
+
return f"edit_file failed: '{find}' not found in file"
|
|
173
|
+
|
|
174
|
+
new_content = original_content.replace(find, replace)
|
|
175
|
+
|
|
176
|
+
with open(path, "w") as f:
|
|
177
|
+
f.write(new_content)
|
|
160
178
|
except Exception as e:
|
|
161
|
-
console.print(" [red]
|
|
179
|
+
console.print(" [red]edit_file failed[/red]")
|
|
162
180
|
console.print(f" [red]{str(e)}[/red]")
|
|
163
|
-
return f"
|
|
181
|
+
return f"edit_file failed: {str(e)}"
|
|
164
182
|
|
|
165
183
|
console.print(" [green]Command succeeded[/green]")
|
|
166
|
-
|
|
167
|
-
return "Command output (exit 0): apply_patch succeeded"
|
|
184
|
+
return f"Successfully edited {path}"
|
|
168
185
|
|
|
169
186
|
def execute(self, command: str, explanation: str) -> str:
|
|
170
187
|
command = command.strip()
|
|
@@ -196,19 +213,27 @@ class TassApp:
|
|
|
196
213
|
console.print(f" [red]{str(e)}[/red]")
|
|
197
214
|
return f"subprocess.run failed: {str(e)}"
|
|
198
215
|
|
|
199
|
-
out = result.stdout
|
|
200
|
-
err = result.stderr
|
|
216
|
+
out = result.stdout
|
|
217
|
+
err = result.stderr
|
|
201
218
|
if result.returncode == 0:
|
|
202
219
|
console.print(" [green]Command succeeded[/green]")
|
|
203
220
|
else:
|
|
204
221
|
console.print(f" [red]Command failed[/red] (code {result.returncode})")
|
|
205
222
|
console.print(f" [red]{err}[/red]")
|
|
206
223
|
|
|
207
|
-
if len(out) >
|
|
208
|
-
|
|
224
|
+
if len(out.split("\n")) > 1000:
|
|
225
|
+
out_first_1000 = "\n".join(out.split("\n")[:1000])
|
|
226
|
+
out = f"{out_first_1000}... (Truncated)"
|
|
227
|
+
|
|
228
|
+
if len(err.split("\n")) > 1000:
|
|
229
|
+
err_first_1000 = "\n".join(err.split("\n")[:1000])
|
|
230
|
+
err = f"{err_first_1000}... (Truncated)"
|
|
231
|
+
|
|
232
|
+
if len(out) > 20000:
|
|
233
|
+
out = f"{out[:20000]}... (Truncated)"
|
|
209
234
|
|
|
210
|
-
if len(err) >
|
|
211
|
-
err = f"{err[:
|
|
235
|
+
if len(err) > 20000:
|
|
236
|
+
err = f"{err[:20000]}... (Truncated)"
|
|
212
237
|
|
|
213
238
|
return f"Command output (exit {result.returncode}):\n{out}\n{err}"
|
|
214
239
|
|
src/constants.py
CHANGED
|
@@ -1,8 +1,5 @@
|
|
|
1
1
|
from pathlib import Path
|
|
2
2
|
|
|
3
|
-
_apply_patch_path = Path(__file__).resolve().parent / "third_party" / "apply_patch.md"
|
|
4
|
-
APPLY_PATCH_PROMPT = _apply_patch_path.read_text().strip()
|
|
5
|
-
|
|
6
3
|
_cwd_path = Path.cwd().resolve()
|
|
7
4
|
|
|
8
5
|
SYSTEM_PROMPT = f"""You are Terminal-Assistant, a helpful AI that executes shell commands based on natural-language requests.
|
|
@@ -11,9 +8,7 @@ If the user's request involves making changes to the filesystem such as creating
|
|
|
11
8
|
|
|
12
9
|
If a user asks for an answer or explanation to something instead of requesting to run a command, answer briefly and concisely. Do not supply extra information, suggestions, tips, or anything of the sort.
|
|
13
10
|
|
|
14
|
-
Current working directory: {_cwd_path}
|
|
15
|
-
|
|
16
|
-
{APPLY_PATCH_PROMPT}"""
|
|
11
|
+
Current working directory: {_cwd_path}"""
|
|
17
12
|
|
|
18
13
|
TOOLS = [
|
|
19
14
|
{
|
|
@@ -41,18 +36,25 @@ TOOLS = [
|
|
|
41
36
|
{
|
|
42
37
|
"type": "function",
|
|
43
38
|
"function": {
|
|
44
|
-
"name": "
|
|
45
|
-
"description": "
|
|
39
|
+
"name": "edit_file",
|
|
40
|
+
"description": "Edits a file. Replaces the instance of 'find' with 'replace'. 'find' and 'replace' are exact strings.The file must be read at least once before calling this tool.",
|
|
46
41
|
"parameters": {
|
|
47
42
|
"type": "object",
|
|
48
43
|
"properties": {
|
|
49
|
-
"
|
|
44
|
+
"path": {
|
|
45
|
+
"type": "string",
|
|
46
|
+
"description": "Relative path of the file",
|
|
47
|
+
},
|
|
48
|
+
"find": {
|
|
49
|
+
"type": "string",
|
|
50
|
+
"description": "The string to find",
|
|
51
|
+
},
|
|
52
|
+
"replace": {
|
|
50
53
|
"type": "string",
|
|
51
|
-
"description": "
|
|
52
|
-
"default": "*** Begin Patch\n*** End Patch\n",
|
|
54
|
+
"description": "The string to replace with",
|
|
53
55
|
},
|
|
54
56
|
},
|
|
55
|
-
"required": ["
|
|
57
|
+
"required": ["path", "find", "replace"],
|
|
56
58
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
|
57
59
|
},
|
|
58
60
|
},
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
src/__init__.py,sha256=tu2q9W5_pkq30l3tRMTGahColBAAubbLP6LaB3l3IFg,89
|
|
2
|
+
src/app.py,sha256=sTPTwDc8KjF9RpL7W5Ix0D0n8ERcWsP1WEVzLWGOKco,9779
|
|
3
|
+
src/cli.py,sha256=op3fYcyfek_KqCCiA-Zdlc9jVZSCi036whMmR2ZjjAs,76
|
|
4
|
+
src/constants.py,sha256=A0_PwEYo1Dpf8UC6HV7JgQwU7GlZQxKhLgwgmyoc3WY,3478
|
|
5
|
+
src/utils.py,sha256=rKq34DVmFbsWPy7R6Bfdvv1ztzFLPT4hUd8BFpPHjqs,681
|
|
6
|
+
tass-0.1.4.dist-info/METADATA,sha256=K1hq1AlWam-s671Nhmb0-X4jj6qAOi8Lfw27wuDxAXA,1071
|
|
7
|
+
tass-0.1.4.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
|
|
8
|
+
tass-0.1.4.dist-info/entry_points.txt,sha256=pviKuIOuHvaQ7_YiFxatJEY8XYfh3EzVWy4LJh0v-A0,38
|
|
9
|
+
tass-0.1.4.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
10
|
+
tass-0.1.4.dist-info/RECORD,,
|
src/third_party/README.md
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
These files are taken directly from https://github.com/openai/gpt-oss to assist with gpt-oss-120b's code editing capabilities. No modifications have been made.
|
src/third_party/__init__.py
DELETED
|
File without changes
|
src/third_party/apply_patch.md
DELETED
|
@@ -1,64 +0,0 @@
|
|
|
1
|
-
When requested to perform coding-related tasks, you MUST adhere to the following criteria when executing the task:
|
|
2
|
-
|
|
3
|
-
- Use `apply_patch` to edit files.
|
|
4
|
-
- If completing the user's task requires writing or modifying files:
|
|
5
|
-
- Your code and final answer should follow these _CODING GUIDELINES_:
|
|
6
|
-
- Avoid unneeded complexity in your solution. Minimize program size.
|
|
7
|
-
- Keep changes consistent with the style of the existing codebase. Changes should be minimal and focused on the task.
|
|
8
|
-
- NEVER add copyright or license headers unless specifically requested.
|
|
9
|
-
- Never implement function stubs. Provide complete working implementations.
|
|
10
|
-
|
|
11
|
-
§ `apply_patch` Specification
|
|
12
|
-
|
|
13
|
-
Your patch language is a stripped‑down, file‑oriented diff format designed to be easy to parse and safe to apply. You can think of it as a high‑level envelope:
|
|
14
|
-
|
|
15
|
-
*** Begin Patch
|
|
16
|
-
[ one or more file sections ]
|
|
17
|
-
*** End Patch
|
|
18
|
-
|
|
19
|
-
Within that envelope, you get a sequence of file operations.
|
|
20
|
-
You MUST include a header to specify the action you are taking.
|
|
21
|
-
Each operation starts with one of three headers:
|
|
22
|
-
|
|
23
|
-
*** Add File: <path> - create a new file. Every following line is a + line (the initial contents).
|
|
24
|
-
*** Delete File: <path> - remove an existing file. Nothing follows.
|
|
25
|
-
*** Update File: <path> - patch an existing file in place (optionally with a rename).
|
|
26
|
-
|
|
27
|
-
May be immediately followed by *** Move to: <new path> if you want to rename the file.
|
|
28
|
-
Then one or more “hunks”, each introduced by @@ (optionally followed by a hunk header).
|
|
29
|
-
Within a hunk each line starts with:
|
|
30
|
-
|
|
31
|
-
- for inserted text,
|
|
32
|
-
|
|
33
|
-
* for removed text, or
|
|
34
|
-
space ( ) for context.
|
|
35
|
-
At the end of a truncated hunk you can emit *** End of File.
|
|
36
|
-
|
|
37
|
-
Patch := Begin { FileOp } End
|
|
38
|
-
Begin := "*** Begin Patch" NEWLINE
|
|
39
|
-
End := "*** End Patch" NEWLINE
|
|
40
|
-
FileOp := AddFile | DeleteFile | UpdateFile
|
|
41
|
-
AddFile := "*** Add File: " path NEWLINE { "+" line NEWLINE }
|
|
42
|
-
DeleteFile := "*** Delete File: " path NEWLINE
|
|
43
|
-
UpdateFile := "*** Update File: " path NEWLINE [ MoveTo ] { Hunk }
|
|
44
|
-
MoveTo := "*** Move to: " newPath NEWLINE
|
|
45
|
-
Hunk := "@@" [ header ] NEWLINE { HunkLine } [ "*** End of File" NEWLINE ]
|
|
46
|
-
HunkLine := (" " | "-" | "+") text NEWLINE
|
|
47
|
-
|
|
48
|
-
A full patch can combine several operations:
|
|
49
|
-
|
|
50
|
-
*** Begin Patch
|
|
51
|
-
*** Add File: hello.txt
|
|
52
|
-
+Hello world
|
|
53
|
-
*** Update File: src/app.py
|
|
54
|
-
*** Move to: src/main.py
|
|
55
|
-
@@ def greet():
|
|
56
|
-
-print("Hi")
|
|
57
|
-
+print("Hello, world!")
|
|
58
|
-
*** Delete File: obsolete.txt
|
|
59
|
-
*** End Patch
|
|
60
|
-
|
|
61
|
-
It is important to remember:
|
|
62
|
-
|
|
63
|
-
- You must include a header with your intended action (Add/Delete/Update)
|
|
64
|
-
- You must prefix new lines with `+` even when creating a new file
|
src/third_party/apply_patch.py
DELETED
|
@@ -1,529 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env python3
|
|
2
|
-
|
|
3
|
-
"""
|
|
4
|
-
A self-contained **pure-Python 3.9+** utility for applying human-readable
|
|
5
|
-
“pseudo-diff” patch files to a collection of text files.
|
|
6
|
-
|
|
7
|
-
Source: https://cookbook.openai.com/examples/gpt4-1_prompting_guide
|
|
8
|
-
"""
|
|
9
|
-
|
|
10
|
-
from __future__ import annotations
|
|
11
|
-
|
|
12
|
-
import pathlib
|
|
13
|
-
from dataclasses import dataclass, field
|
|
14
|
-
from enum import Enum
|
|
15
|
-
from typing import (
|
|
16
|
-
Callable,
|
|
17
|
-
Dict,
|
|
18
|
-
List,
|
|
19
|
-
Optional,
|
|
20
|
-
Tuple,
|
|
21
|
-
Union,
|
|
22
|
-
)
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
# --------------------------------------------------------------------------- #
|
|
26
|
-
# Domain objects
|
|
27
|
-
# --------------------------------------------------------------------------- #
|
|
28
|
-
class ActionType(str, Enum):
|
|
29
|
-
ADD = "add"
|
|
30
|
-
DELETE = "delete"
|
|
31
|
-
UPDATE = "update"
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
@dataclass
|
|
35
|
-
class FileChange:
|
|
36
|
-
type: ActionType
|
|
37
|
-
old_content: Optional[str] = None
|
|
38
|
-
new_content: Optional[str] = None
|
|
39
|
-
move_path: Optional[str] = None
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
@dataclass
|
|
43
|
-
class Commit:
|
|
44
|
-
changes: Dict[str, FileChange] = field(default_factory=dict)
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
# --------------------------------------------------------------------------- #
|
|
48
|
-
# Exceptions
|
|
49
|
-
# --------------------------------------------------------------------------- #
|
|
50
|
-
class DiffError(ValueError):
|
|
51
|
-
"""Any problem detected while parsing or applying a patch."""
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
# --------------------------------------------------------------------------- #
|
|
55
|
-
# Helper dataclasses used while parsing patches
|
|
56
|
-
# --------------------------------------------------------------------------- #
|
|
57
|
-
@dataclass
|
|
58
|
-
class Chunk:
|
|
59
|
-
orig_index: int = -1
|
|
60
|
-
del_lines: List[str] = field(default_factory=list)
|
|
61
|
-
ins_lines: List[str] = field(default_factory=list)
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
@dataclass
|
|
65
|
-
class PatchAction:
|
|
66
|
-
type: ActionType
|
|
67
|
-
new_file: Optional[str] = None
|
|
68
|
-
chunks: List[Chunk] = field(default_factory=list)
|
|
69
|
-
move_path: Optional[str] = None
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
@dataclass
|
|
73
|
-
class Patch:
|
|
74
|
-
actions: Dict[str, PatchAction] = field(default_factory=dict)
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
# --------------------------------------------------------------------------- #
|
|
78
|
-
# Patch text parser
|
|
79
|
-
# --------------------------------------------------------------------------- #
|
|
80
|
-
@dataclass
|
|
81
|
-
class Parser:
|
|
82
|
-
current_files: Dict[str, str]
|
|
83
|
-
lines: List[str]
|
|
84
|
-
index: int = 0
|
|
85
|
-
patch: Patch = field(default_factory=Patch)
|
|
86
|
-
fuzz: int = 0
|
|
87
|
-
|
|
88
|
-
# ------------- low-level helpers -------------------------------------- #
|
|
89
|
-
def _cur_line(self) -> str:
|
|
90
|
-
if self.index >= len(self.lines):
|
|
91
|
-
raise DiffError("Unexpected end of input while parsing patch")
|
|
92
|
-
return self.lines[self.index]
|
|
93
|
-
|
|
94
|
-
@staticmethod
|
|
95
|
-
def _norm(line: str) -> str:
|
|
96
|
-
"""Strip CR so comparisons work for both LF and CRLF input."""
|
|
97
|
-
return line.rstrip("\r")
|
|
98
|
-
|
|
99
|
-
# ------------- scanning convenience ----------------------------------- #
|
|
100
|
-
def is_done(self, prefixes: Optional[Tuple[str, ...]] = None) -> bool:
|
|
101
|
-
if self.index >= len(self.lines):
|
|
102
|
-
return True
|
|
103
|
-
if (
|
|
104
|
-
prefixes
|
|
105
|
-
and len(prefixes) > 0
|
|
106
|
-
and self._norm(self._cur_line()).startswith(prefixes)
|
|
107
|
-
):
|
|
108
|
-
return True
|
|
109
|
-
return False
|
|
110
|
-
|
|
111
|
-
def startswith(self, prefix: Union[str, Tuple[str, ...]]) -> bool:
|
|
112
|
-
return self._norm(self._cur_line()).startswith(prefix)
|
|
113
|
-
|
|
114
|
-
def read_str(self, prefix: str) -> str:
|
|
115
|
-
"""
|
|
116
|
-
Consume the current line if it starts with *prefix* and return the text
|
|
117
|
-
**after** the prefix. Raises if prefix is empty.
|
|
118
|
-
"""
|
|
119
|
-
if prefix == "":
|
|
120
|
-
raise ValueError("read_str() requires a non-empty prefix")
|
|
121
|
-
if self._norm(self._cur_line()).startswith(prefix):
|
|
122
|
-
text = self._cur_line()[len(prefix) :]
|
|
123
|
-
self.index += 1
|
|
124
|
-
return text
|
|
125
|
-
return ""
|
|
126
|
-
|
|
127
|
-
def read_line(self) -> str:
|
|
128
|
-
"""Return the current raw line and advance."""
|
|
129
|
-
line = self._cur_line()
|
|
130
|
-
self.index += 1
|
|
131
|
-
return line
|
|
132
|
-
|
|
133
|
-
# ------------- public entry point -------------------------------------- #
|
|
134
|
-
def parse(self) -> None:
|
|
135
|
-
while not self.is_done(("*** End Patch",)):
|
|
136
|
-
# ---------- UPDATE ---------- #
|
|
137
|
-
path = self.read_str("*** Update File: ")
|
|
138
|
-
if path:
|
|
139
|
-
if path in self.patch.actions:
|
|
140
|
-
raise DiffError(f"Duplicate update for file: {path}")
|
|
141
|
-
move_to = self.read_str("*** Move to: ")
|
|
142
|
-
if path not in self.current_files:
|
|
143
|
-
raise DiffError(f"Update File Error - missing file: {path}")
|
|
144
|
-
text = self.current_files[path]
|
|
145
|
-
action = self._parse_update_file(text)
|
|
146
|
-
action.move_path = move_to or None
|
|
147
|
-
self.patch.actions[path] = action
|
|
148
|
-
continue
|
|
149
|
-
|
|
150
|
-
# ---------- DELETE ---------- #
|
|
151
|
-
path = self.read_str("*** Delete File: ")
|
|
152
|
-
if path:
|
|
153
|
-
if path in self.patch.actions:
|
|
154
|
-
raise DiffError(f"Duplicate delete for file: {path}")
|
|
155
|
-
if path not in self.current_files:
|
|
156
|
-
raise DiffError(f"Delete File Error - missing file: {path}")
|
|
157
|
-
self.patch.actions[path] = PatchAction(type=ActionType.DELETE)
|
|
158
|
-
continue
|
|
159
|
-
|
|
160
|
-
# ---------- ADD ---------- #
|
|
161
|
-
path = self.read_str("*** Add File: ")
|
|
162
|
-
if path:
|
|
163
|
-
if path in self.patch.actions:
|
|
164
|
-
raise DiffError(f"Duplicate add for file: {path}")
|
|
165
|
-
if path in self.current_files:
|
|
166
|
-
raise DiffError(f"Add File Error - file already exists: {path}")
|
|
167
|
-
self.patch.actions[path] = self._parse_add_file()
|
|
168
|
-
continue
|
|
169
|
-
|
|
170
|
-
raise DiffError(f"Unknown line while parsing: {self._cur_line()}")
|
|
171
|
-
|
|
172
|
-
if not self.startswith("*** End Patch"):
|
|
173
|
-
raise DiffError("Missing *** End Patch sentinel")
|
|
174
|
-
self.index += 1 # consume sentinel
|
|
175
|
-
|
|
176
|
-
# ------------- section parsers ---------------------------------------- #
|
|
177
|
-
def _parse_update_file(self, text: str) -> PatchAction:
|
|
178
|
-
action = PatchAction(type=ActionType.UPDATE)
|
|
179
|
-
lines = text.split("\n")
|
|
180
|
-
index = 0
|
|
181
|
-
while not self.is_done(
|
|
182
|
-
(
|
|
183
|
-
"*** End Patch",
|
|
184
|
-
"*** Update File:",
|
|
185
|
-
"*** Delete File:",
|
|
186
|
-
"*** Add File:",
|
|
187
|
-
"*** End of File",
|
|
188
|
-
)
|
|
189
|
-
):
|
|
190
|
-
def_str = self.read_str("@@ ")
|
|
191
|
-
section_str = ""
|
|
192
|
-
if not def_str and self._norm(self._cur_line()) == "@@":
|
|
193
|
-
section_str = self.read_line()
|
|
194
|
-
|
|
195
|
-
if not (def_str or section_str or index == 0):
|
|
196
|
-
raise DiffError(f"Invalid line in update section:\n{self._cur_line()}")
|
|
197
|
-
|
|
198
|
-
if def_str.strip():
|
|
199
|
-
found = False
|
|
200
|
-
if def_str not in lines[:index]:
|
|
201
|
-
for i, s in enumerate(lines[index:], index):
|
|
202
|
-
if s == def_str:
|
|
203
|
-
index = i + 1
|
|
204
|
-
found = True
|
|
205
|
-
break
|
|
206
|
-
if not found and def_str.strip() not in [
|
|
207
|
-
s.strip() for s in lines[:index]
|
|
208
|
-
]:
|
|
209
|
-
for i, s in enumerate(lines[index:], index):
|
|
210
|
-
if s.strip() == def_str.strip():
|
|
211
|
-
index = i + 1
|
|
212
|
-
self.fuzz += 1
|
|
213
|
-
found = True
|
|
214
|
-
break
|
|
215
|
-
|
|
216
|
-
next_ctx, chunks, end_idx, eof = peek_next_section(self.lines, self.index)
|
|
217
|
-
new_index, fuzz = find_context(lines, next_ctx, index, eof)
|
|
218
|
-
if new_index == -1:
|
|
219
|
-
ctx_txt = "\n".join(next_ctx)
|
|
220
|
-
raise DiffError(
|
|
221
|
-
f"Invalid {'EOF ' if eof else ''}context at {index}:\n{ctx_txt}"
|
|
222
|
-
)
|
|
223
|
-
self.fuzz += fuzz
|
|
224
|
-
for ch in chunks:
|
|
225
|
-
ch.orig_index += new_index
|
|
226
|
-
action.chunks.append(ch)
|
|
227
|
-
index = new_index + len(next_ctx)
|
|
228
|
-
self.index = end_idx
|
|
229
|
-
return action
|
|
230
|
-
|
|
231
|
-
def _parse_add_file(self) -> PatchAction:
|
|
232
|
-
lines: List[str] = []
|
|
233
|
-
while not self.is_done(
|
|
234
|
-
("*** End Patch", "*** Update File:", "*** Delete File:", "*** Add File:")
|
|
235
|
-
):
|
|
236
|
-
s = self.read_line()
|
|
237
|
-
if not s.startswith("+"):
|
|
238
|
-
raise DiffError(f"Invalid Add File line (missing '+'): {s}")
|
|
239
|
-
lines.append(s[1:]) # strip leading '+'
|
|
240
|
-
return PatchAction(type=ActionType.ADD, new_file="\n".join(lines))
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
# --------------------------------------------------------------------------- #
|
|
244
|
-
# Helper functions
|
|
245
|
-
# --------------------------------------------------------------------------- #
|
|
246
|
-
def find_context_core(
|
|
247
|
-
lines: List[str], context: List[str], start: int
|
|
248
|
-
) -> Tuple[int, int]:
|
|
249
|
-
if not context:
|
|
250
|
-
return start, 0
|
|
251
|
-
|
|
252
|
-
for i in range(start, len(lines)):
|
|
253
|
-
if lines[i : i + len(context)] == context:
|
|
254
|
-
return i, 0
|
|
255
|
-
for i in range(start, len(lines)):
|
|
256
|
-
if [s.rstrip() for s in lines[i : i + len(context)]] == [
|
|
257
|
-
s.rstrip() for s in context
|
|
258
|
-
]:
|
|
259
|
-
return i, 1
|
|
260
|
-
for i in range(start, len(lines)):
|
|
261
|
-
if [s.strip() for s in lines[i : i + len(context)]] == [
|
|
262
|
-
s.strip() for s in context
|
|
263
|
-
]:
|
|
264
|
-
return i, 100
|
|
265
|
-
return -1, 0
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
def find_context(
|
|
269
|
-
lines: List[str], context: List[str], start: int, eof: bool
|
|
270
|
-
) -> Tuple[int, int]:
|
|
271
|
-
if eof:
|
|
272
|
-
new_index, fuzz = find_context_core(lines, context, len(lines) - len(context))
|
|
273
|
-
if new_index != -1:
|
|
274
|
-
return new_index, fuzz
|
|
275
|
-
new_index, fuzz = find_context_core(lines, context, start)
|
|
276
|
-
return new_index, fuzz + 10_000
|
|
277
|
-
return find_context_core(lines, context, start)
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
def peek_next_section(
|
|
281
|
-
lines: List[str], index: int
|
|
282
|
-
) -> Tuple[List[str], List[Chunk], int, bool]:
|
|
283
|
-
old: List[str] = []
|
|
284
|
-
del_lines: List[str] = []
|
|
285
|
-
ins_lines: List[str] = []
|
|
286
|
-
chunks: List[Chunk] = []
|
|
287
|
-
mode = "keep"
|
|
288
|
-
orig_index = index
|
|
289
|
-
|
|
290
|
-
while index < len(lines):
|
|
291
|
-
s = lines[index]
|
|
292
|
-
if s.startswith(
|
|
293
|
-
(
|
|
294
|
-
"@@",
|
|
295
|
-
"*** End Patch",
|
|
296
|
-
"*** Update File:",
|
|
297
|
-
"*** Delete File:",
|
|
298
|
-
"*** Add File:",
|
|
299
|
-
"*** End of File",
|
|
300
|
-
)
|
|
301
|
-
):
|
|
302
|
-
break
|
|
303
|
-
if s == "***":
|
|
304
|
-
break
|
|
305
|
-
if s.startswith("***"):
|
|
306
|
-
raise DiffError(f"Invalid Line: {s}")
|
|
307
|
-
index += 1
|
|
308
|
-
|
|
309
|
-
last_mode = mode
|
|
310
|
-
if s == "":
|
|
311
|
-
s = " "
|
|
312
|
-
if s[0] == "+":
|
|
313
|
-
mode = "add"
|
|
314
|
-
elif s[0] == "-":
|
|
315
|
-
mode = "delete"
|
|
316
|
-
elif s[0] == " ":
|
|
317
|
-
mode = "keep"
|
|
318
|
-
else:
|
|
319
|
-
raise DiffError(f"Invalid Line: {s}")
|
|
320
|
-
s = s[1:]
|
|
321
|
-
|
|
322
|
-
if mode == "keep" and last_mode != mode:
|
|
323
|
-
if ins_lines or del_lines:
|
|
324
|
-
chunks.append(
|
|
325
|
-
Chunk(
|
|
326
|
-
orig_index=len(old) - len(del_lines),
|
|
327
|
-
del_lines=del_lines,
|
|
328
|
-
ins_lines=ins_lines,
|
|
329
|
-
)
|
|
330
|
-
)
|
|
331
|
-
del_lines, ins_lines = [], []
|
|
332
|
-
|
|
333
|
-
if mode == "delete":
|
|
334
|
-
del_lines.append(s)
|
|
335
|
-
old.append(s)
|
|
336
|
-
elif mode == "add":
|
|
337
|
-
ins_lines.append(s)
|
|
338
|
-
elif mode == "keep":
|
|
339
|
-
old.append(s)
|
|
340
|
-
|
|
341
|
-
if ins_lines or del_lines:
|
|
342
|
-
chunks.append(
|
|
343
|
-
Chunk(
|
|
344
|
-
orig_index=len(old) - len(del_lines),
|
|
345
|
-
del_lines=del_lines,
|
|
346
|
-
ins_lines=ins_lines,
|
|
347
|
-
)
|
|
348
|
-
)
|
|
349
|
-
|
|
350
|
-
if index < len(lines) and lines[index] == "*** End of File":
|
|
351
|
-
index += 1
|
|
352
|
-
return old, chunks, index, True
|
|
353
|
-
|
|
354
|
-
if index == orig_index:
|
|
355
|
-
raise DiffError("Nothing in this section")
|
|
356
|
-
return old, chunks, index, False
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
# --------------------------------------------------------------------------- #
|
|
360
|
-
# Patch → Commit and Commit application
|
|
361
|
-
# --------------------------------------------------------------------------- #
|
|
362
|
-
def _get_updated_file(text: str, action: PatchAction, path: str) -> str:
|
|
363
|
-
if action.type is not ActionType.UPDATE:
|
|
364
|
-
raise DiffError("_get_updated_file called with non-update action")
|
|
365
|
-
orig_lines = text.split("\n")
|
|
366
|
-
dest_lines: List[str] = []
|
|
367
|
-
orig_index = 0
|
|
368
|
-
|
|
369
|
-
for chunk in action.chunks:
|
|
370
|
-
if chunk.orig_index > len(orig_lines):
|
|
371
|
-
raise DiffError(
|
|
372
|
-
f"{path}: chunk.orig_index {chunk.orig_index} exceeds file length"
|
|
373
|
-
)
|
|
374
|
-
if orig_index > chunk.orig_index:
|
|
375
|
-
raise DiffError(
|
|
376
|
-
f"{path}: overlapping chunks at {orig_index} > {chunk.orig_index}"
|
|
377
|
-
)
|
|
378
|
-
|
|
379
|
-
dest_lines.extend(orig_lines[orig_index : chunk.orig_index])
|
|
380
|
-
orig_index = chunk.orig_index
|
|
381
|
-
|
|
382
|
-
dest_lines.extend(chunk.ins_lines)
|
|
383
|
-
orig_index += len(chunk.del_lines)
|
|
384
|
-
|
|
385
|
-
dest_lines.extend(orig_lines[orig_index:])
|
|
386
|
-
return "\n".join(dest_lines)
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
def patch_to_commit(patch: Patch, orig: Dict[str, str]) -> Commit:
|
|
390
|
-
commit = Commit()
|
|
391
|
-
for path, action in patch.actions.items():
|
|
392
|
-
if action.type is ActionType.DELETE:
|
|
393
|
-
commit.changes[path] = FileChange(
|
|
394
|
-
type=ActionType.DELETE, old_content=orig[path]
|
|
395
|
-
)
|
|
396
|
-
elif action.type is ActionType.ADD:
|
|
397
|
-
if action.new_file is None:
|
|
398
|
-
raise DiffError("ADD action without file content")
|
|
399
|
-
commit.changes[path] = FileChange(
|
|
400
|
-
type=ActionType.ADD, new_content=action.new_file
|
|
401
|
-
)
|
|
402
|
-
elif action.type is ActionType.UPDATE:
|
|
403
|
-
new_content = _get_updated_file(orig[path], action, path)
|
|
404
|
-
commit.changes[path] = FileChange(
|
|
405
|
-
type=ActionType.UPDATE,
|
|
406
|
-
old_content=orig[path],
|
|
407
|
-
new_content=new_content,
|
|
408
|
-
move_path=action.move_path,
|
|
409
|
-
)
|
|
410
|
-
return commit
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
# --------------------------------------------------------------------------- #
|
|
414
|
-
# User-facing helpers
|
|
415
|
-
# --------------------------------------------------------------------------- #
|
|
416
|
-
def text_to_patch(text: str, orig: Dict[str, str]) -> Tuple[Patch, int]:
|
|
417
|
-
lines = text.splitlines() # preserves blank lines, no strip()
|
|
418
|
-
if (
|
|
419
|
-
len(lines) < 2
|
|
420
|
-
or not Parser._norm(lines[0]).startswith("*** Begin Patch")
|
|
421
|
-
or Parser._norm(lines[-1]) != "*** End Patch"
|
|
422
|
-
):
|
|
423
|
-
raise DiffError("Invalid patch text - missing sentinels")
|
|
424
|
-
|
|
425
|
-
parser = Parser(current_files=orig, lines=lines, index=1)
|
|
426
|
-
parser.parse()
|
|
427
|
-
return parser.patch, parser.fuzz
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
def identify_files_needed(text: str) -> List[str]:
|
|
431
|
-
lines = text.splitlines()
|
|
432
|
-
return [
|
|
433
|
-
line[len("*** Update File: ") :]
|
|
434
|
-
for line in lines
|
|
435
|
-
if line.startswith("*** Update File: ")
|
|
436
|
-
] + [
|
|
437
|
-
line[len("*** Delete File: ") :]
|
|
438
|
-
for line in lines
|
|
439
|
-
if line.startswith("*** Delete File: ")
|
|
440
|
-
]
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
def identify_files_added(text: str) -> List[str]:
|
|
444
|
-
lines = text.splitlines()
|
|
445
|
-
return [
|
|
446
|
-
line[len("*** Add File: ") :]
|
|
447
|
-
for line in lines
|
|
448
|
-
if line.startswith("*** Add File: ")
|
|
449
|
-
]
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
# --------------------------------------------------------------------------- #
|
|
453
|
-
# File-system helpers
|
|
454
|
-
# --------------------------------------------------------------------------- #
|
|
455
|
-
def load_files(paths: List[str], open_fn: Callable[[str], str]) -> Dict[str, str]:
|
|
456
|
-
return {path: open_fn(path) for path in paths}
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
def apply_commit(
|
|
460
|
-
commit: Commit,
|
|
461
|
-
write_fn: Callable[[str, str], None],
|
|
462
|
-
remove_fn: Callable[[str], None],
|
|
463
|
-
) -> None:
|
|
464
|
-
for path, change in commit.changes.items():
|
|
465
|
-
if change.type is ActionType.DELETE:
|
|
466
|
-
remove_fn(path)
|
|
467
|
-
elif change.type is ActionType.ADD:
|
|
468
|
-
if change.new_content is None:
|
|
469
|
-
raise DiffError(f"ADD change for {path} has no content")
|
|
470
|
-
write_fn(path, change.new_content)
|
|
471
|
-
elif change.type is ActionType.UPDATE:
|
|
472
|
-
if change.new_content is None:
|
|
473
|
-
raise DiffError(f"UPDATE change for {path} has no new content")
|
|
474
|
-
target = change.move_path or path
|
|
475
|
-
write_fn(target, change.new_content)
|
|
476
|
-
if change.move_path:
|
|
477
|
-
remove_fn(path)
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
def open_file(path: str) -> str:
|
|
481
|
-
with open(path, "rt", encoding="utf-8") as fh:
|
|
482
|
-
return fh.read()
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
def write_file(path: str, content: str) -> None:
|
|
486
|
-
target = pathlib.Path(path)
|
|
487
|
-
target.parent.mkdir(parents=True, exist_ok=True)
|
|
488
|
-
with target.open("wt", encoding="utf-8") as fh:
|
|
489
|
-
fh.write(content)
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
def remove_file(path: str) -> None:
|
|
493
|
-
pathlib.Path(path).unlink(missing_ok=True)
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
def apply_patch(
|
|
498
|
-
text: str,
|
|
499
|
-
open_fn: Callable[[str], str] = open_file,
|
|
500
|
-
write_fn: Callable[[str, str], None] = write_file,
|
|
501
|
-
remove_fn: Callable[[str], None] = remove_file,
|
|
502
|
-
) -> str:
|
|
503
|
-
if not text.startswith("*** Begin Patch"):
|
|
504
|
-
raise DiffError("Patch text must start with *** Begin Patch")
|
|
505
|
-
paths = identify_files_needed(text)
|
|
506
|
-
orig = load_files(paths, open_fn)
|
|
507
|
-
patch, _fuzz = text_to_patch(text, orig)
|
|
508
|
-
commit = patch_to_commit(patch, orig)
|
|
509
|
-
apply_commit(commit, write_fn, remove_fn)
|
|
510
|
-
return "Done!"
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
def main() -> None:
|
|
514
|
-
import sys
|
|
515
|
-
|
|
516
|
-
patch_text = sys.stdin.read()
|
|
517
|
-
if not patch_text:
|
|
518
|
-
print("Please pass patch text through stdin", file=sys.stderr)
|
|
519
|
-
return
|
|
520
|
-
try:
|
|
521
|
-
result = apply_patch(patch_text)
|
|
522
|
-
except DiffError as exc:
|
|
523
|
-
print(exc, file=sys.stderr)
|
|
524
|
-
return
|
|
525
|
-
print(result)
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
if __name__ == "__main__":
|
|
529
|
-
main()
|
tass-0.1.2.dist-info/RECORD
DELETED
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
src/__init__.py,sha256=tu2q9W5_pkq30l3tRMTGahColBAAubbLP6LaB3l3IFg,89
|
|
2
|
-
src/app.py,sha256=SG7jAfU49OtTTkuKSl7bIr-A5enrNLXZ0YZleTd7Qf0,8640
|
|
3
|
-
src/cli.py,sha256=op3fYcyfek_KqCCiA-Zdlc9jVZSCi036whMmR2ZjjAs,76
|
|
4
|
-
src/constants.py,sha256=Mhhm6JJII7NsTFhHVP0VA34gBKaXV00hkhWS0pSJJbk,3225
|
|
5
|
-
src/utils.py,sha256=rKq34DVmFbsWPy7R6Bfdvv1ztzFLPT4hUd8BFpPHjqs,681
|
|
6
|
-
src/third_party/README.md,sha256=fjgAoAM_Vp1xOCdSYZT1menMom5dVDXa48h9VbDJfVI,160
|
|
7
|
-
src/third_party/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
8
|
-
src/third_party/apply_patch.md,sha256=Q0bRVZepyrP0wF-IzNiNEfkXYcbFKJ42y7Hrl5Uxyfc,2578
|
|
9
|
-
src/third_party/apply_patch.py,sha256=zZNWPp4bKuvHikGFQ_aHtDaWZ2ZH39c59J9Fb6NprCE,17575
|
|
10
|
-
tass-0.1.2.dist-info/METADATA,sha256=vPQZSIRPdrFAlb4XNSGSj6gpF-k9fxdLmihDOstnDkU,1071
|
|
11
|
-
tass-0.1.2.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
|
|
12
|
-
tass-0.1.2.dist-info/entry_points.txt,sha256=pviKuIOuHvaQ7_YiFxatJEY8XYfh3EzVWy4LJh0v-A0,38
|
|
13
|
-
tass-0.1.2.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
14
|
-
tass-0.1.2.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|