tass 0.1.1__tar.gz → 0.1.3__tar.gz
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.
- {tass-0.1.1 → tass-0.1.3}/PKG-INFO +1 -1
- {tass-0.1.1 → tass-0.1.3}/pyproject.toml +1 -1
- tass-0.1.3/src/app.py +269 -0
- {tass-0.1.1 → tass-0.1.3}/src/constants.py +18 -10
- {tass-0.1.1 → tass-0.1.3}/src/utils.py +5 -0
- {tass-0.1.1 → tass-0.1.3}/uv.lock +1 -1
- tass-0.1.1/src/app.py +0 -187
- tass-0.1.1/src/third_party/README.md +0 -1
- tass-0.1.1/src/third_party/__init__.py +0 -0
- tass-0.1.1/src/third_party/apply_patch.md +0 -64
- tass-0.1.1/src/third_party/apply_patch.py +0 -529
- {tass-0.1.1 → tass-0.1.3}/.gitignore +0 -0
- {tass-0.1.1 → tass-0.1.3}/.python-version +0 -0
- {tass-0.1.1 → tass-0.1.3}/LICENSE +0 -0
- {tass-0.1.1 → tass-0.1.3}/README.md +0 -0
- {tass-0.1.1 → tass-0.1.3}/src/__init__.py +0 -0
- {tass-0.1.1 → tass-0.1.3}/src/cli.py +0 -0
- {tass-0.1.1 → tass-0.1.3}/tests/test_utils.py +0 -0
tass-0.1.3/src/app.py
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import os
|
|
3
|
+
import subprocess
|
|
4
|
+
|
|
5
|
+
import requests
|
|
6
|
+
from rich.console import Console
|
|
7
|
+
from rich.markdown import Markdown
|
|
8
|
+
|
|
9
|
+
from src.constants import (
|
|
10
|
+
SYSTEM_PROMPT,
|
|
11
|
+
TOOLS,
|
|
12
|
+
)
|
|
13
|
+
from src.utils import (
|
|
14
|
+
is_read_only_command,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
console = Console()
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class TassApp:
|
|
21
|
+
|
|
22
|
+
def __init__(self):
|
|
23
|
+
self.messages: list[dict] = [{"role": "system", "content": SYSTEM_PROMPT}]
|
|
24
|
+
self.host = os.environ.get("TASS_HOST", "http://localhost:8080")
|
|
25
|
+
self.TOOLS_MAP = {
|
|
26
|
+
"execute": self.execute,
|
|
27
|
+
"read_file": self.read_file,
|
|
28
|
+
"edit_file": self.edit_file,
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
def _check_llm_host(self):
|
|
32
|
+
test_url = f"{self.host}/v1/models"
|
|
33
|
+
try:
|
|
34
|
+
response = requests.get(test_url, timeout=2)
|
|
35
|
+
console.print("Terminal Assistant [green](LLM connection ✓)[/green]")
|
|
36
|
+
if response.status_code == 200:
|
|
37
|
+
return
|
|
38
|
+
except Exception:
|
|
39
|
+
console.print("Terminal Assistant [red](LLM connection ✗)[/red]")
|
|
40
|
+
|
|
41
|
+
console.print("\n[red]Could not connect to LLM[/red]")
|
|
42
|
+
console.print(f"If your LLM isn't running on {self.host}, you can set the [bold]TASS_HOST[/] environment variable to a different URL.")
|
|
43
|
+
new_host = console.input(
|
|
44
|
+
"Enter a different URL for this session (or press Enter to keep current): "
|
|
45
|
+
).strip()
|
|
46
|
+
|
|
47
|
+
if new_host:
|
|
48
|
+
self.host = new_host
|
|
49
|
+
|
|
50
|
+
try:
|
|
51
|
+
response = requests.get(f"{self.host}/v1/models", timeout=2)
|
|
52
|
+
if response.status_code == 200:
|
|
53
|
+
console.print(f"[green]Connection established to {self.host}[/green]")
|
|
54
|
+
return
|
|
55
|
+
except Exception:
|
|
56
|
+
console.print(f"[red]Unable to verify new host {self.host}. Continuing with it anyway.[/red]")
|
|
57
|
+
|
|
58
|
+
def summarize(self):
|
|
59
|
+
max_messages = 10
|
|
60
|
+
if len(self.messages) <= max_messages:
|
|
61
|
+
return
|
|
62
|
+
|
|
63
|
+
prompt = (
|
|
64
|
+
"The conversation is becoming long and might soon go beyond the "
|
|
65
|
+
"context limit. Please provide a concise summary of the conversation, "
|
|
66
|
+
"preserving all important details. Keep the summary short enough "
|
|
67
|
+
"to fit within a few paragraphs at the most."
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
response = requests.post(
|
|
71
|
+
f"{self.host}/v1/chat/completions",
|
|
72
|
+
json={
|
|
73
|
+
"messages": self.messages + [{"role": "user", "content": prompt}],
|
|
74
|
+
"chat_template_kwargs": {"reasoning_effort": "medium"},
|
|
75
|
+
},
|
|
76
|
+
)
|
|
77
|
+
data = response.json()
|
|
78
|
+
summary = data["choices"][0]["message"]["content"]
|
|
79
|
+
self.messages = [self.messages[0], {"role": "assistant", "content": f"Summary of the conversation so far:\n{summary}"}]
|
|
80
|
+
|
|
81
|
+
def call_llm(self) -> str | None:
|
|
82
|
+
response = requests.post(
|
|
83
|
+
f"{self.host}/v1/chat/completions",
|
|
84
|
+
json={
|
|
85
|
+
"messages": self.messages,
|
|
86
|
+
"tools": TOOLS,
|
|
87
|
+
"chat_template_kwargs": {
|
|
88
|
+
"reasoning_effort": "medium",
|
|
89
|
+
}
|
|
90
|
+
},
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
data = response.json()
|
|
94
|
+
message = data["choices"][0]["message"]
|
|
95
|
+
if not message.get("tool_calls"):
|
|
96
|
+
return message["content"]
|
|
97
|
+
|
|
98
|
+
tool_name = message["tool_calls"][0]["function"]["name"]
|
|
99
|
+
tool_args_str = message["tool_calls"][0]["function"]["arguments"]
|
|
100
|
+
self.messages.append(
|
|
101
|
+
{
|
|
102
|
+
"role": "assistant",
|
|
103
|
+
"tool_calls": [
|
|
104
|
+
{
|
|
105
|
+
"index": 0,
|
|
106
|
+
"id": "id1",
|
|
107
|
+
"type": "function",
|
|
108
|
+
"function": {
|
|
109
|
+
"name": tool_name,
|
|
110
|
+
"arguments": tool_args_str
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
]
|
|
114
|
+
}
|
|
115
|
+
)
|
|
116
|
+
try:
|
|
117
|
+
tool = self.TOOLS_MAP[tool_name]
|
|
118
|
+
tool_args = json.loads(tool_args_str)
|
|
119
|
+
result = tool(**tool_args)
|
|
120
|
+
self.messages.append({"role": "tool", "content": result})
|
|
121
|
+
return None
|
|
122
|
+
except Exception as e:
|
|
123
|
+
self.messages.append({"role": "user", "content": str(e)})
|
|
124
|
+
return self.call_llm()
|
|
125
|
+
|
|
126
|
+
def read_file(self, path: str, start: int = 1) -> str:
|
|
127
|
+
console.print(f" └ Reading file [bold]{path}[/]...")
|
|
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
|
+
|
|
137
|
+
lines = []
|
|
138
|
+
line_num = 1
|
|
139
|
+
for line in out.split("\n"):
|
|
140
|
+
if line_num < start:
|
|
141
|
+
line_num += 1
|
|
142
|
+
continue
|
|
143
|
+
|
|
144
|
+
lines.append(line)
|
|
145
|
+
line_num += 1
|
|
146
|
+
|
|
147
|
+
if len(lines) >= 1000:
|
|
148
|
+
lines.append("... (truncated)")
|
|
149
|
+
break
|
|
150
|
+
|
|
151
|
+
console.print(" [green]Command succeeded[/green]")
|
|
152
|
+
return "".join(lines)
|
|
153
|
+
|
|
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")])
|
|
157
|
+
console.print()
|
|
158
|
+
console.print(Markdown(f"```diff\nEditing {path}\n{find_with_minuses}\n{replace_with_pluses}\n```"))
|
|
159
|
+
answer = console.input("\n[bold]Run?[/] ([bold]Y[/]/n): ").strip().lower()
|
|
160
|
+
if answer not in ("yes", "y", ""):
|
|
161
|
+
reason = console.input("Why not? (optional, press Enter to skip): ").strip()
|
|
162
|
+
return f"User declined: {reason or 'no reason'}"
|
|
163
|
+
|
|
164
|
+
console.print(" └ Running...")
|
|
165
|
+
try:
|
|
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)
|
|
178
|
+
except Exception as e:
|
|
179
|
+
console.print(" [red]edit_file failed[/red]")
|
|
180
|
+
console.print(f" [red]{str(e)}[/red]")
|
|
181
|
+
return f"edit_file failed: {str(e)}"
|
|
182
|
+
|
|
183
|
+
console.print(" [green]Command succeeded[/green]")
|
|
184
|
+
return f"Successfully edited {path}"
|
|
185
|
+
|
|
186
|
+
def execute(self, command: str, explanation: str) -> str:
|
|
187
|
+
command = command.strip()
|
|
188
|
+
requires_confirmation = not is_read_only_command(command)
|
|
189
|
+
if requires_confirmation:
|
|
190
|
+
console.print()
|
|
191
|
+
console.print(Markdown(f"```shell\n{command}\n```"))
|
|
192
|
+
if explanation:
|
|
193
|
+
console.print(f"Explanation: {explanation}")
|
|
194
|
+
answer = console.input("\n[bold]Run?[/] ([bold]Y[/]/n): ").strip().lower()
|
|
195
|
+
if answer not in ("yes", "y", ""):
|
|
196
|
+
reason = console.input("Why not? (optional, press Enter to skip): ").strip()
|
|
197
|
+
return f"User declined: {reason or 'no reason'}"
|
|
198
|
+
|
|
199
|
+
if requires_confirmation:
|
|
200
|
+
console.print(" └ Running...")
|
|
201
|
+
else:
|
|
202
|
+
console.print(f" └ Running [bold]{command}[/] (Explanation: {explanation})...")
|
|
203
|
+
|
|
204
|
+
try:
|
|
205
|
+
result = subprocess.run(
|
|
206
|
+
command,
|
|
207
|
+
shell=True,
|
|
208
|
+
capture_output=True,
|
|
209
|
+
text=True,
|
|
210
|
+
)
|
|
211
|
+
except Exception as e:
|
|
212
|
+
console.print(" [red]subprocess.run failed[/red]")
|
|
213
|
+
console.print(f" [red]{str(e)}[/red]")
|
|
214
|
+
return f"subprocess.run failed: {str(e)}"
|
|
215
|
+
|
|
216
|
+
out = result.stdout
|
|
217
|
+
err = result.stderr
|
|
218
|
+
if result.returncode == 0:
|
|
219
|
+
console.print(" [green]Command succeeded[/green]")
|
|
220
|
+
else:
|
|
221
|
+
console.print(f" [red]Command failed[/red] (code {result.returncode})")
|
|
222
|
+
console.print(f" [red]{err}[/red]")
|
|
223
|
+
|
|
224
|
+
if len(out.split("\n")) > 5000:
|
|
225
|
+
out_first_1000 = "\n".join(out.split("\n")[:1000])
|
|
226
|
+
out = f"{out_first_1000}... (Truncated)"
|
|
227
|
+
|
|
228
|
+
if len(err) > 5000:
|
|
229
|
+
err_first_1000 = "\n".join(err.split("\n")[:1000])
|
|
230
|
+
err = f"{err_first_1000}... (Truncated)"
|
|
231
|
+
|
|
232
|
+
return f"Command output (exit {result.returncode}):\n{out}\n{err}"
|
|
233
|
+
|
|
234
|
+
def run(self):
|
|
235
|
+
try:
|
|
236
|
+
self._check_llm_host()
|
|
237
|
+
except KeyboardInterrupt:
|
|
238
|
+
console.print("\nBye!")
|
|
239
|
+
return
|
|
240
|
+
|
|
241
|
+
while True:
|
|
242
|
+
try:
|
|
243
|
+
user_input = console.input("\n> ").strip()
|
|
244
|
+
except KeyboardInterrupt:
|
|
245
|
+
console.print("\nBye!")
|
|
246
|
+
break
|
|
247
|
+
|
|
248
|
+
if not user_input:
|
|
249
|
+
continue
|
|
250
|
+
|
|
251
|
+
if user_input.lower().strip() == "exit":
|
|
252
|
+
console.print("\nBye!")
|
|
253
|
+
break
|
|
254
|
+
|
|
255
|
+
self.messages.append({"role": "user", "content": user_input})
|
|
256
|
+
|
|
257
|
+
while True:
|
|
258
|
+
try:
|
|
259
|
+
llm_resp = self.call_llm()
|
|
260
|
+
except Exception as e:
|
|
261
|
+
console.print(f"Failed to call LLM: {str(e)}")
|
|
262
|
+
break
|
|
263
|
+
|
|
264
|
+
if llm_resp is not None:
|
|
265
|
+
console.print("")
|
|
266
|
+
console.print(Markdown(llm_resp))
|
|
267
|
+
self.messages.append({"role": "assistant", "content": llm_resp})
|
|
268
|
+
self.summarize()
|
|
269
|
+
break
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
from pathlib import Path
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
APPLY_PATCH_PROMPT = _apply_patch_path.read_text().strip()
|
|
3
|
+
_cwd_path = Path.cwd().resolve()
|
|
5
4
|
|
|
6
5
|
SYSTEM_PROMPT = f"""You are Terminal-Assistant, a helpful AI that executes shell commands based on natural-language requests.
|
|
7
6
|
|
|
@@ -9,7 +8,7 @@ If the user's request involves making changes to the filesystem such as creating
|
|
|
9
8
|
|
|
10
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.
|
|
11
10
|
|
|
12
|
-
{
|
|
11
|
+
Current working directory: {_cwd_path}"""
|
|
13
12
|
|
|
14
13
|
TOOLS = [
|
|
15
14
|
{
|
|
@@ -26,7 +25,7 @@ TOOLS = [
|
|
|
26
25
|
},
|
|
27
26
|
"explanation": {
|
|
28
27
|
"type": "string",
|
|
29
|
-
"description": "A brief explanation of why you want to run this command.",
|
|
28
|
+
"description": "A brief explanation of why you want to run this command. Keep it to a single sentence.",
|
|
30
29
|
},
|
|
31
30
|
},
|
|
32
31
|
"required": ["command", "explanation"],
|
|
@@ -37,18 +36,25 @@ TOOLS = [
|
|
|
37
36
|
{
|
|
38
37
|
"type": "function",
|
|
39
38
|
"function": {
|
|
40
|
-
"name": "
|
|
41
|
-
"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.",
|
|
42
41
|
"parameters": {
|
|
43
42
|
"type": "object",
|
|
44
43
|
"properties": {
|
|
45
|
-
"
|
|
44
|
+
"path": {
|
|
45
|
+
"type": "string",
|
|
46
|
+
"description": "Relative path of the file",
|
|
47
|
+
},
|
|
48
|
+
"find": {
|
|
46
49
|
"type": "string",
|
|
47
|
-
"description": "
|
|
48
|
-
|
|
50
|
+
"description": "The string to find",
|
|
51
|
+
},
|
|
52
|
+
"replace": {
|
|
53
|
+
"type": "string",
|
|
54
|
+
"description": "The string to replace with",
|
|
49
55
|
},
|
|
50
56
|
},
|
|
51
|
-
"required": ["
|
|
57
|
+
"required": ["path", "find", "replace"],
|
|
52
58
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
|
53
59
|
},
|
|
54
60
|
},
|
|
@@ -84,6 +90,7 @@ READ_ONLY_COMMANDS = [
|
|
|
84
90
|
"less",
|
|
85
91
|
"more",
|
|
86
92
|
"echo",
|
|
93
|
+
"head",
|
|
87
94
|
"tail",
|
|
88
95
|
"wc",
|
|
89
96
|
"grep",
|
|
@@ -91,4 +98,5 @@ READ_ONLY_COMMANDS = [
|
|
|
91
98
|
"ack",
|
|
92
99
|
"which",
|
|
93
100
|
"sed",
|
|
101
|
+
"find",
|
|
94
102
|
]
|
|
@@ -10,6 +10,11 @@ def is_read_only_command(command: str) -> bool:
|
|
|
10
10
|
if ">" in command:
|
|
11
11
|
return False
|
|
12
12
|
|
|
13
|
+
# Replace everything that potentially runs another command with a pipe
|
|
14
|
+
command = command.replace("&&", "|")
|
|
15
|
+
command = command.replace("||", "|")
|
|
16
|
+
command = command.replace(";", "|")
|
|
17
|
+
|
|
13
18
|
pipes = command.split("|")
|
|
14
19
|
for pipe in pipes:
|
|
15
20
|
if pipe.strip().split()[0] not in READ_ONLY_COMMANDS:
|
tass-0.1.1/src/app.py
DELETED
|
@@ -1,187 +0,0 @@
|
|
|
1
|
-
import json
|
|
2
|
-
import os
|
|
3
|
-
import subprocess
|
|
4
|
-
|
|
5
|
-
import requests
|
|
6
|
-
from rich.console import Console
|
|
7
|
-
from rich.markdown import Markdown
|
|
8
|
-
|
|
9
|
-
from src.constants import (
|
|
10
|
-
SYSTEM_PROMPT,
|
|
11
|
-
TOOLS,
|
|
12
|
-
)
|
|
13
|
-
from src.third_party.apply_patch import apply_patch
|
|
14
|
-
from src.utils import (
|
|
15
|
-
is_read_only_command,
|
|
16
|
-
)
|
|
17
|
-
|
|
18
|
-
console = Console()
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
class TassApp:
|
|
22
|
-
|
|
23
|
-
def __init__(self):
|
|
24
|
-
self.messages: list[dict] = [{"role": "system", "content": SYSTEM_PROMPT}]
|
|
25
|
-
self.host = os.environ.get("TASS_HOST", "http://localhost:8080")
|
|
26
|
-
self.TOOLS_MAP = {
|
|
27
|
-
"execute": self.execute,
|
|
28
|
-
"apply_patch": self.apply_patch_tass,
|
|
29
|
-
"read_file": self.read_file,
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
def call_llm(self) -> str | None:
|
|
33
|
-
response = requests.post(
|
|
34
|
-
f"{self.host}/v1/chat/completions",
|
|
35
|
-
json={
|
|
36
|
-
"messages": self.messages,
|
|
37
|
-
"tools": TOOLS,
|
|
38
|
-
"chat_template_kwargs": {
|
|
39
|
-
"reasoning_effort": "medium",
|
|
40
|
-
}
|
|
41
|
-
},
|
|
42
|
-
)
|
|
43
|
-
|
|
44
|
-
data = response.json()
|
|
45
|
-
message = data["choices"][0]["message"]
|
|
46
|
-
if message.get("tool_calls"):
|
|
47
|
-
tool_name = message["tool_calls"][0]["function"]["name"]
|
|
48
|
-
tool_args_str = message["tool_calls"][0]["function"]["arguments"]
|
|
49
|
-
self.messages.append(
|
|
50
|
-
{
|
|
51
|
-
"role": "assistant",
|
|
52
|
-
"tool_calls": [
|
|
53
|
-
{
|
|
54
|
-
"index": 0,
|
|
55
|
-
"id": "id1",
|
|
56
|
-
"type": "function",
|
|
57
|
-
"function": {
|
|
58
|
-
"name": tool_name,
|
|
59
|
-
"arguments": tool_args_str
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
]
|
|
63
|
-
}
|
|
64
|
-
)
|
|
65
|
-
try:
|
|
66
|
-
tool = self.TOOLS_MAP[tool_name]
|
|
67
|
-
tool_args = json.loads(tool_args_str)
|
|
68
|
-
result = tool(**tool_args)
|
|
69
|
-
self.messages.append({"role": "tool", "content": result})
|
|
70
|
-
except Exception as e:
|
|
71
|
-
self.messages.append({"role": "user", "content": str(e)})
|
|
72
|
-
return self.call_llm()
|
|
73
|
-
|
|
74
|
-
return data["choices"][0]["message"]["content"]
|
|
75
|
-
|
|
76
|
-
def read_file(self, path: str, start: int = 1) -> str:
|
|
77
|
-
console.print(f" └ Reading file [bold]{path}[/]...")
|
|
78
|
-
|
|
79
|
-
lines = []
|
|
80
|
-
with open(path) as f:
|
|
81
|
-
line_num = 1
|
|
82
|
-
for line in f:
|
|
83
|
-
if line_num < start:
|
|
84
|
-
line_num += 1
|
|
85
|
-
continue
|
|
86
|
-
|
|
87
|
-
lines.append(line)
|
|
88
|
-
line_num += 1
|
|
89
|
-
|
|
90
|
-
if len(lines) >= 1000:
|
|
91
|
-
break
|
|
92
|
-
|
|
93
|
-
console.print(" [green]Command succeeded[/green]")
|
|
94
|
-
return "".join(lines)
|
|
95
|
-
|
|
96
|
-
def apply_patch_tass(self, patch: str) -> str:
|
|
97
|
-
console.print()
|
|
98
|
-
console.print(Markdown(f"```diff\n{patch}\n```"))
|
|
99
|
-
answer = console.input("\n[bold]Run?[/] ([bold]Y[/]/n): ").strip().lower()
|
|
100
|
-
if answer not in ("yes", "y", ""):
|
|
101
|
-
reason = console.input("Why not? (optional, press Enter to skip): ").strip()
|
|
102
|
-
return f"User declined: {reason or 'no reason'}"
|
|
103
|
-
|
|
104
|
-
console.print(" └ Running...")
|
|
105
|
-
|
|
106
|
-
try:
|
|
107
|
-
apply_patch(patch)
|
|
108
|
-
except Exception as e:
|
|
109
|
-
console.print(" [red]apply_patch failed[/red]")
|
|
110
|
-
console.print(f" [red]{str(e)}[/red]")
|
|
111
|
-
return f"apply_patch failed: {str(e)}"
|
|
112
|
-
|
|
113
|
-
console.print(" [green]Command succeeded[/green]")
|
|
114
|
-
|
|
115
|
-
return "Command output (exit 0): apply_patch succeeded"
|
|
116
|
-
|
|
117
|
-
def execute(self, command: str, explanation: str) -> str:
|
|
118
|
-
command = command.strip()
|
|
119
|
-
requires_confirmation = not is_read_only_command(command)
|
|
120
|
-
if requires_confirmation:
|
|
121
|
-
console.print()
|
|
122
|
-
console.print(Markdown(f"```shell\n{command}\n```"))
|
|
123
|
-
if explanation:
|
|
124
|
-
console.print(f"Explanation: {explanation}")
|
|
125
|
-
answer = console.input("\n[bold]Run?[/] ([bold]Y[/]/n): ").strip().lower()
|
|
126
|
-
if answer not in ("yes", "y", ""):
|
|
127
|
-
reason = console.input("Why not? (optional, press Enter to skip): ").strip()
|
|
128
|
-
return f"User declined: {reason or 'no reason'}"
|
|
129
|
-
|
|
130
|
-
if requires_confirmation:
|
|
131
|
-
console.print(" └ Running...")
|
|
132
|
-
else:
|
|
133
|
-
console.print(f" └ Running [bold]{command}[/] (Explanation: {explanation})...")
|
|
134
|
-
|
|
135
|
-
try:
|
|
136
|
-
result = subprocess.run(
|
|
137
|
-
command,
|
|
138
|
-
shell=True,
|
|
139
|
-
capture_output=True,
|
|
140
|
-
text=True,
|
|
141
|
-
)
|
|
142
|
-
except Exception as e:
|
|
143
|
-
console.print(" [red]subprocess.run failed[/red]")
|
|
144
|
-
console.print(f" [red]{str(e)}[/red]")
|
|
145
|
-
return f"subprocess.run failed: {str(e)}"
|
|
146
|
-
|
|
147
|
-
out = result.stdout.strip()
|
|
148
|
-
err = result.stderr.strip()
|
|
149
|
-
if result.returncode == 0:
|
|
150
|
-
console.print(" [green]Command succeeded[/green]")
|
|
151
|
-
else:
|
|
152
|
-
console.print(f" [red]Command failed[/red] (code {result.returncode})")
|
|
153
|
-
console.print(f" [red]{err}[/red]")
|
|
154
|
-
|
|
155
|
-
if len(out) > 5000:
|
|
156
|
-
out = f"{out[:5000]}... (Truncated)"
|
|
157
|
-
|
|
158
|
-
if len(err) > 5000:
|
|
159
|
-
err = f"{err[:5000]}... (Truncated)"
|
|
160
|
-
|
|
161
|
-
return f"Command output (exit {result.returncode}):\n{out}\n{err}"
|
|
162
|
-
|
|
163
|
-
def run(self):
|
|
164
|
-
console.print("Terminal Assistant")
|
|
165
|
-
|
|
166
|
-
while True:
|
|
167
|
-
try:
|
|
168
|
-
user_input = console.input("\n> ").strip()
|
|
169
|
-
except KeyboardInterrupt:
|
|
170
|
-
console.print("\nBye!")
|
|
171
|
-
break
|
|
172
|
-
|
|
173
|
-
if not user_input:
|
|
174
|
-
continue
|
|
175
|
-
|
|
176
|
-
if user_input.lower().strip() == "exit":
|
|
177
|
-
console.print("\nBye!")
|
|
178
|
-
break
|
|
179
|
-
|
|
180
|
-
self.messages.append({"role": "user", "content": user_input})
|
|
181
|
-
|
|
182
|
-
while True:
|
|
183
|
-
llm_resp = self.call_llm()
|
|
184
|
-
if llm_resp is not None:
|
|
185
|
-
console.print("")
|
|
186
|
-
console.print(Markdown(llm_resp))
|
|
187
|
-
break
|
|
@@ -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.
|
|
File without changes
|
|
@@ -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
|
|
@@ -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()
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|