tass 0.1.1__py3-none-any.whl → 0.1.3__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 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,10 +24,60 @@ 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
 
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
+
32
81
  def call_llm(self) -> str | None:
33
82
  response = requests.post(
34
83
  f"{self.host}/v1/chat/completions",
@@ -43,76 +92,96 @@ class TassApp:
43
92
 
44
93
  data = response.json()
45
94
  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
- }
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
61
111
  }
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"]
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()
75
125
 
76
126
  def read_file(self, path: str, start: int = 1) -> str:
77
127
  console.print(f" └ Reading file [bold]{path}[/]...")
78
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
+
79
137
  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)
138
+ line_num = 1
139
+ for line in out.split("\n"):
140
+ if line_num < start:
88
141
  line_num += 1
142
+ continue
89
143
 
90
- if len(lines) >= 1000:
91
- break
144
+ lines.append(line)
145
+ line_num += 1
146
+
147
+ if len(lines) >= 1000:
148
+ lines.append("... (truncated)")
149
+ break
92
150
 
93
151
  console.print(" [green]Command succeeded[/green]")
94
152
  return "".join(lines)
95
153
 
96
- def apply_patch_tass(self, patch: str) -> str:
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")])
97
157
  console.print()
98
- console.print(Markdown(f"```diff\n{patch}\n```"))
158
+ console.print(Markdown(f"```diff\nEditing {path}\n{find_with_minuses}\n{replace_with_pluses}\n```"))
99
159
  answer = console.input("\n[bold]Run?[/] ([bold]Y[/]/n): ").strip().lower()
100
160
  if answer not in ("yes", "y", ""):
101
161
  reason = console.input("Why not? (optional, press Enter to skip): ").strip()
102
162
  return f"User declined: {reason or 'no reason'}"
103
163
 
104
164
  console.print(" └ Running...")
105
-
106
165
  try:
107
- apply_patch(patch)
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)
108
178
  except Exception as e:
109
- console.print(" [red]apply_patch failed[/red]")
179
+ console.print(" [red]edit_file failed[/red]")
110
180
  console.print(f" [red]{str(e)}[/red]")
111
- return f"apply_patch failed: {str(e)}"
181
+ return f"edit_file failed: {str(e)}"
112
182
 
113
183
  console.print(" [green]Command succeeded[/green]")
114
-
115
- return "Command output (exit 0): apply_patch succeeded"
184
+ return f"Successfully edited {path}"
116
185
 
117
186
  def execute(self, command: str, explanation: str) -> str:
118
187
  command = command.strip()
@@ -144,24 +213,30 @@ class TassApp:
144
213
  console.print(f" [red]{str(e)}[/red]")
145
214
  return f"subprocess.run failed: {str(e)}"
146
215
 
147
- out = result.stdout.strip()
148
- err = result.stderr.strip()
216
+ out = result.stdout
217
+ err = result.stderr
149
218
  if result.returncode == 0:
150
219
  console.print(" [green]Command succeeded[/green]")
151
220
  else:
152
221
  console.print(f" [red]Command failed[/red] (code {result.returncode})")
153
222
  console.print(f" [red]{err}[/red]")
154
223
 
155
- if len(out) > 5000:
156
- out = f"{out[:5000]}... (Truncated)"
224
+ if len(out.split("\n")) > 5000:
225
+ out_first_1000 = "\n".join(out.split("\n")[:1000])
226
+ out = f"{out_first_1000}... (Truncated)"
157
227
 
158
228
  if len(err) > 5000:
159
- err = f"{err[:5000]}... (Truncated)"
229
+ err_first_1000 = "\n".join(err.split("\n")[:1000])
230
+ err = f"{err_first_1000}... (Truncated)"
160
231
 
161
232
  return f"Command output (exit {result.returncode}):\n{out}\n{err}"
162
233
 
163
234
  def run(self):
164
- console.print("Terminal Assistant")
235
+ try:
236
+ self._check_llm_host()
237
+ except KeyboardInterrupt:
238
+ console.print("\nBye!")
239
+ return
165
240
 
166
241
  while True:
167
242
  try:
@@ -180,8 +255,15 @@ class TassApp:
180
255
  self.messages.append({"role": "user", "content": user_input})
181
256
 
182
257
  while True:
183
- llm_resp = self.call_llm()
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
+
184
264
  if llm_resp is not None:
185
265
  console.print("")
186
266
  console.print(Markdown(llm_resp))
267
+ self.messages.append({"role": "assistant", "content": llm_resp})
268
+ self.summarize()
187
269
  break
src/constants.py CHANGED
@@ -1,7 +1,6 @@
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()
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
- {APPLY_PATCH_PROMPT}"""
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": "apply_patch",
41
- "description": "Patch a file",
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
- "patch": {
44
+ "path": {
45
+ "type": "string",
46
+ "description": "Relative path of the file",
47
+ },
48
+ "find": {
46
49
  "type": "string",
47
- "description": "Formatted patch code",
48
- "default": "*** Begin Patch\n*** End Patch\n",
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": ["patch"],
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
  ]
src/utils.py CHANGED
@@ -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:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tass
3
- Version: 0.1.1
3
+ Version: 0.1.3
4
4
  Summary: A terminal assistant that allows you to ask an LLM to run commands.
5
5
  Project-URL: Homepage, https://github.com/cetincan0/tass
6
6
  Author: Can Cetin
@@ -0,0 +1,10 @@
1
+ src/__init__.py,sha256=tu2q9W5_pkq30l3tRMTGahColBAAubbLP6LaB3l3IFg,89
2
+ src/app.py,sha256=jy-6wYh-Wb2Z1DOVWKc7stEX3gtt6dM9BfJOv6ZG9SE,9607
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.3.dist-info/METADATA,sha256=uS8VJaj57K9T-LlxZkOy1iQdCSTu_UrLhIocIihJtew,1071
7
+ tass-0.1.3.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
8
+ tass-0.1.3.dist-info/entry_points.txt,sha256=pviKuIOuHvaQ7_YiFxatJEY8XYfh3EzVWy4LJh0v-A0,38
9
+ tass-0.1.3.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
10
+ tass-0.1.3.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.
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()
@@ -1,14 +0,0 @@
1
- src/__init__.py,sha256=tu2q9W5_pkq30l3tRMTGahColBAAubbLP6LaB3l3IFg,89
2
- src/app.py,sha256=8_nX46VV4avs20lqSRL__L0iu7igSiZkV7xjZ1A2fRY,6182
3
- src/cli.py,sha256=op3fYcyfek_KqCCiA-Zdlc9jVZSCi036whMmR2ZjjAs,76
4
- src/constants.py,sha256=qzqqLwVp6bVCbelvxGZlSYSnMKZFEjFvBWF-bW86ER8,3097
5
- src/utils.py,sha256=KLVKfTECfSCXqSkWmT9rK1wtjFvb6FJhusy5q7FGO_A,483
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.1.dist-info/METADATA,sha256=hAqKbUGBW_bjz308J-RqJrV3ydTxkx8hT9D7Y34gzQw,1071
11
- tass-0.1.1.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
12
- tass-0.1.1.dist-info/entry_points.txt,sha256=pviKuIOuHvaQ7_YiFxatJEY8XYfh3EzVWy4LJh0v-A0,38
13
- tass-0.1.1.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
14
- tass-0.1.1.dist-info/RECORD,,
File without changes