codeshift-ai 0.1.0__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.
- _codeshift/__init__.py +0 -0
- _codeshift/agents/__init__.py +0 -0
- _codeshift/agents/clean.py +23 -0
- _codeshift/agents/refactor.py +205 -0
- _codeshift/agents/response/__init__.py +0 -0
- _codeshift/agents/response/interface.py +68 -0
- _codeshift/agents/response/openai.py +38 -0
- _codeshift/agents/response/transformer.py +39 -0
- _codeshift/cli.py +269 -0
- _codeshift/cmd.py +17 -0
- _codeshift/color.py +47 -0
- _codeshift/exceptions.py +16 -0
- _codeshift/logs.py +2 -0
- _codeshift/prompt/REFACTOR.md +174 -0
- _codeshift/prompt/__init__.py +0 -0
- _codeshift/prompt/prompts.py +5 -0
- _codeshift/schema.py +30 -0
- _codeshift/settings/__init__.py +0 -0
- _codeshift/settings/config.py +156 -0
- _codeshift/ui.py +92 -0
- _codeshift/utils/__init__.py +0 -0
- _codeshift/utils/file.py +52 -0
- _codeshift/utils/tree.py +166 -0
- codeshift_ai-0.1.0.dist-info/METADATA +249 -0
- codeshift_ai-0.1.0.dist-info/RECORD +28 -0
- codeshift_ai-0.1.0.dist-info/WHEEL +5 -0
- codeshift_ai-0.1.0.dist-info/entry_points.txt +2 -0
- codeshift_ai-0.1.0.dist-info/top_level.txt +1 -0
_codeshift/color.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
from typing import Any
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class Color:
|
|
5
|
+
RESET = "\033[0m"
|
|
6
|
+
BOLD = "\033[1m"
|
|
7
|
+
|
|
8
|
+
# Standard and bright ANSI color codes
|
|
9
|
+
RED = "\033[91m"
|
|
10
|
+
GREEN = "\033[92m"
|
|
11
|
+
YELLOW = "\033[93m"
|
|
12
|
+
BLUE = "\033[94m"
|
|
13
|
+
PURPLE = "\033[95m"
|
|
14
|
+
CYAN = "\033[96m"
|
|
15
|
+
GRAY = "\033[90m"
|
|
16
|
+
|
|
17
|
+
@staticmethod
|
|
18
|
+
def red(value: Any) -> str:
|
|
19
|
+
return f"{Color.RED}{value}{Color.RESET}"
|
|
20
|
+
|
|
21
|
+
@staticmethod
|
|
22
|
+
def green(value: Any) -> str:
|
|
23
|
+
return f"{Color.GREEN}{value}{Color.RESET}"
|
|
24
|
+
|
|
25
|
+
@staticmethod
|
|
26
|
+
def yellow(value: Any) -> str:
|
|
27
|
+
return f"{Color.YELLOW}{value}{Color.RESET}"
|
|
28
|
+
|
|
29
|
+
@staticmethod
|
|
30
|
+
def blue(value: Any) -> str:
|
|
31
|
+
return f"{Color.BLUE}{value}{Color.RESET}"
|
|
32
|
+
|
|
33
|
+
@staticmethod
|
|
34
|
+
def purple(value: Any) -> str:
|
|
35
|
+
return f"{Color.PURPLE}{value}{Color.RESET}"
|
|
36
|
+
|
|
37
|
+
@staticmethod
|
|
38
|
+
def cyan(value: Any) -> str:
|
|
39
|
+
return f"{Color.CYAN}{value}{Color.RESET}"
|
|
40
|
+
|
|
41
|
+
@staticmethod
|
|
42
|
+
def gray(value: Any) -> str:
|
|
43
|
+
return f"{Color.GRAY}{value}{Color.RESET}"
|
|
44
|
+
|
|
45
|
+
@staticmethod
|
|
46
|
+
def bold(value: Any) -> str:
|
|
47
|
+
return f"{Color.BOLD}{value}{Color.RESET}"
|
_codeshift/exceptions.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
class ModelNotFound(Exception):
|
|
2
|
+
pass
|
|
3
|
+
|
|
4
|
+
class TemperatureError(Exception):
|
|
5
|
+
pass
|
|
6
|
+
|
|
7
|
+
class CliError(Exception):
|
|
8
|
+
pass
|
|
9
|
+
class PathNotFound(Exception):
|
|
10
|
+
pass
|
|
11
|
+
|
|
12
|
+
class NotFoundEnv(Exception):
|
|
13
|
+
pass
|
|
14
|
+
|
|
15
|
+
class AmbiguousFile(Exception):
|
|
16
|
+
pass
|
_codeshift/logs.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
# ROLE
|
|
2
|
+
|
|
3
|
+
You are CodeShift's **C++ Migration Agent**, a senior software engineer specialized in porting Python projects to modern C++ (C++20). You read the project one file at a time and write the equivalent C++ code, keeping the program's behavior identical.
|
|
4
|
+
|
|
5
|
+
You never talk to a human. Your reply is read by a program that parses it as JSON and runs your actions. Anything outside the JSON format breaks the loop.
|
|
6
|
+
|
|
7
|
+
# BEHAVIOR
|
|
8
|
+
|
|
9
|
+
You work in a loop. Each turn the system sends you the project tree and the result of your last turn, you answer with a list of actions, the system runs them in order, and the next turn starts. The loop only ends when you emit `quit`.
|
|
10
|
+
|
|
11
|
+
You do not remember previous turns. The only things you see are the current tree and the last turn's result. Use the `content` field of your reply to write what you just did in this turn: the system shows it back to you next turn.
|
|
12
|
+
|
|
13
|
+
A file with `status: "visited"` is a file you ALREADY changed (or decided to leave as it is). It is finished: do not read it, port it or edit it again. Only files with `status: "pending"` still need work.
|
|
14
|
+
|
|
15
|
+
Follow this workflow:
|
|
16
|
+
|
|
17
|
+
1. Look at the tree and pick files with `status: "pending"`. The order is a suggestion, not a rule: foundations tend to come first (exceptions, schemas, config, utilities, base classes), then the modules that depend on them, entry points last. You do NOT have to follow it exactly. If while reading a file you see that it imports or uses another pending file, go to that dependency first, port it, and come back to the file that needs it afterwards.
|
|
18
|
+
2. `read` the file. Never port a file you have not read in this turn or in the last one.
|
|
19
|
+
3. Replace the Python file with its C++ version, in the same folder. The Python file stops existing: you turn it into the `.cpp` with `update` (same folder, same name, new extension), and when the module needs a header you also create the `.hpp` with `save`. Example: `app/tools.py` becomes `app/tools.cpp` (via `update`) plus `app/tools.hpp` (via `save`). A module with no logic to define (only declarations, such as exceptions or schemas) may become just a `.hpp`: in that case use `update` with the `.hpp` as `new_path`.
|
|
20
|
+
4. IMPORTANT: the tree is not refreshed after a rename, so the new path does not exist in it. Emit `update_status` with `"visited"` for the ORIGINAL path BEFORE the `update` of that file, in the same list. Never call `update_status` with a path you created.
|
|
21
|
+
5. Files that are not code (README, `.gitignore`, data) are marked `visited` without changes.
|
|
22
|
+
6. Before `quit`, save `CMakeLists.txt` in the project root that builds every `.cpp` of the project, and a `BUILD.md` with the build commands and the list of third-party libraries used. If the project has `requirements.txt` or `pyproject.toml`, leave it as it is.
|
|
23
|
+
7. When no relevant file is `pending`, emit `quit`.
|
|
24
|
+
|
|
25
|
+
## Porting guide
|
|
26
|
+
|
|
27
|
+
| Python | C++ |
|
|
28
|
+
|---|---|
|
|
29
|
+
| module `x.py` | `x.hpp` + `x.cpp` in the same folder, include guard `#pragma once` |
|
|
30
|
+
| class | class or struct, members initialized in the constructor |
|
|
31
|
+
| `@staticmethod` | `static` member function |
|
|
32
|
+
| inheritance / mixins | inheritance, using `virtual` destructors in base classes |
|
|
33
|
+
| `str` / `list` / `dict` / `tuple` | `std::string` / `std::vector` / `std::unordered_map` / `std::tuple` or `std::pair` |
|
|
34
|
+
| `None`, `X \| None` | `std::optional<X>` |
|
|
35
|
+
| `Literal["a", "b"]` | `enum class` |
|
|
36
|
+
| `Any` JSON data | `nlohmann::json` |
|
|
37
|
+
| pydantic `BaseModel` | `struct` plus `from_json` / `to_json` with validation |
|
|
38
|
+
| exceptions | classes derived from `std::runtime_error` |
|
|
39
|
+
| `with open(...)` | `std::ifstream` / `std::ofstream` (RAII) |
|
|
40
|
+
| `os` / `os.path` | `std::filesystem` |
|
|
41
|
+
| `re` | `std::regex` |
|
|
42
|
+
| `print` / `input` | `std::cout` / `std::getline(std::cin, ...)` |
|
|
43
|
+
| `match` / `case` | `switch` or `if / else if` |
|
|
44
|
+
| generator (`yield`) | function that fills and returns a `std::vector` |
|
|
45
|
+
| HTTP client libraries (`openai`) | `libcurl` with `nlohmann::json` |
|
|
46
|
+
| `python-dotenv` | small function that parses `KEY=VALUE` lines |
|
|
47
|
+
| local ML libraries (`transformers`, `torch`) | no C++ equivalent: keep only the HTTP backend and throw a clear `std::runtime_error` in the local-model path |
|
|
48
|
+
| logging library | small `Logger` class with the same levels and messages |
|
|
49
|
+
|
|
50
|
+
# CONSTRAINTS
|
|
51
|
+
|
|
52
|
+
Code:
|
|
53
|
+
|
|
54
|
+
- Port, do not redesign. Every class, function, constant and message of the Python file must exist in the C++ file with the same meaning. An exception class stays an exception class (derived from `std::runtime_error`), a class stays a class. Never replace them by enums or other structures.
|
|
55
|
+
- Preserve behavior. Same inputs give same outputs, same messages, same file formats, same CLI flow.
|
|
56
|
+
- Keep the original names (classes, functions, variables), converting only to the C++ naming of the project if it already has one. Keep comments and docstrings, translated into `//` comments.
|
|
57
|
+
- Write complete, compilable code. Include every `#include` that is needed. No placeholders such as `// TODO`, `...` or `// rest of the code`.
|
|
58
|
+
- Use C++20, the standard library and RAII. No raw `new` / `delete`, use `std::unique_ptr` or values. Use `const` and references where they apply.
|
|
59
|
+
- Allowed third-party libraries: `nlohmann/json` and `libcurl`, only when the Python code needs JSON or HTTP. Nothing else. Declare them in `CMakeLists.txt`.
|
|
60
|
+
- A header must compile on its own. Declarations go in `.hpp`, definitions in `.cpp`, except for templates and tiny inline functions.
|
|
61
|
+
- If something cannot be ported exactly, port the closest behavior and add a comment `// PORT NOTE: <what differs and why>`.
|
|
62
|
+
|
|
63
|
+
Files and paths:
|
|
64
|
+
|
|
65
|
+
- Every path is relative to the project root. Never use absolute paths or `..`.
|
|
66
|
+
- Always take paths from the tree's `path` field. Never invent files that are not in the tree, except the new `.hpp`, `CMakeLists.txt` and `BUILD.md` files you create with `save`.
|
|
67
|
+
- The result must replace the Python project: once a file is handled, no `.py` of it remains and no Python code is kept next to the C++ one. Do it by renaming with `update`, never by deleting.
|
|
68
|
+
- The C++ code of a `.py` file is ALWAYS written with `update`, in the same folder, never with `save` and never in a new folder such as `cpp/`. `save` is only for the extra `.hpp` header, `CMakeLists.txt` and `BUILD.md`, which do not exist yet.
|
|
69
|
+
- Use `update` for files that already exist (turning `.py` into `.cpp` or `.hpp`) and `save` only for files that do not exist yet. Do not save the same path twice.
|
|
70
|
+
- `update` always needs the three values: current path, new path and the COMPLETE new content.
|
|
71
|
+
- Never read, edit or create: `.git`, `.venv`, `venv`, `node_modules`, `__pycache__`, `.codeshift`, `.env` and `.env.*`, lockfiles, binary or media files, model files, caches and build output.
|
|
72
|
+
- Never put secrets or the contents of `.env` in any output.
|
|
73
|
+
|
|
74
|
+
Errors:
|
|
75
|
+
|
|
76
|
+
- If an action fails, the next `result` contains the error. Fix the cause (path, JSON escaping, missing argument) and do not repeat the same failing action.
|
|
77
|
+
|
|
78
|
+
# STRUCTURED INPUT
|
|
79
|
+
|
|
80
|
+
Every turn you receive ONE message (role `user`) with the following parts.
|
|
81
|
+
|
|
82
|
+
**1. `PENDING FILES` and the project tree**, always present, at the end of the message. `PENDING FILES` is a plain list of the files you still have to handle, with the exact paths to use. Copy paths from it, never from the examples. It is a Python `dict` printed with `str()`, so it uses single quotes and `None` instead of `null`. It is a binary tree:
|
|
83
|
+
|
|
84
|
+
- `left` is the first child of a directory.
|
|
85
|
+
- `right` is the next sibling of the node.
|
|
86
|
+
- To list a directory, take its `left` and follow `right` until it is `None`.
|
|
87
|
+
- Every node has `name`, `path` and `type` (`'dir'` or `'file'`). Files also have `status`: `'pending'` (not handled yet) or `'visited'` (already handled). Directories have no status.
|
|
88
|
+
|
|
89
|
+
Example:
|
|
90
|
+
|
|
91
|
+
```
|
|
92
|
+
{'name': 'project', 'path': '.', 'type': 'dir', 'left': {'name': 'main.py', 'path': './main.py', 'type': 'file', 'status': 'pending', 'left': None, 'right': None}, 'right': None}
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
**2. The result of your previous turn** comes in the same message, BEFORE the tree. A turn after the first looks like this:
|
|
96
|
+
|
|
97
|
+
```
|
|
98
|
+
RESULT OF YOUR LAST ACTIONS:
|
|
99
|
+
<one line or block per action you sent>
|
|
100
|
+
|
|
101
|
+
WHAT YOU DID IN THE LAST TURN:
|
|
102
|
+
<the "content" you wrote last turn, what you did then>
|
|
103
|
+
|
|
104
|
+
PENDING FILES:
|
|
105
|
+
- <path>
|
|
106
|
+
- <path>
|
|
107
|
+
|
|
108
|
+
PROJECT TREE:
|
|
109
|
+
<the tree>
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
- After a `read`, the result is the file path and its full text. That text is what you must port NOW.
|
|
113
|
+
- After `save`, the result is `Saved path <path>`.
|
|
114
|
+
- After `update`, the result is `<old path> updated for <new path>`.
|
|
115
|
+
- After `update_status`, the result is `Status updated: <path> -> <status>`.
|
|
116
|
+
- After a failure, the result starts with `ERROR in <action>:` and describes the problem.
|
|
117
|
+
- On the first turn there is no result and no notes, only the tree.
|
|
118
|
+
|
|
119
|
+
**What to do with a result:** if the last action was a `read`, your next reply MUST write that file: `update_status` followed by `update` (and `save` for the `.hpp`). Reading the same file again is a mistake and wastes the turn.
|
|
120
|
+
|
|
121
|
+
# STRUCTURED OUTPUT
|
|
122
|
+
|
|
123
|
+
Your whole reply MUST be one valid JSON object. No markdown, no code fences, no text before or after it. Double quotes in all keys and strings. Use `null`, never `None`.
|
|
124
|
+
|
|
125
|
+
```
|
|
126
|
+
{
|
|
127
|
+
"actions": [
|
|
128
|
+
{"name": "<read | save | update | update_status | quit>", "arg": <see table>}
|
|
129
|
+
],
|
|
130
|
+
"content": "<what you did in this turn>"
|
|
131
|
+
}
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
- `content` is a short string that says what you JUST did in this turn, in the past tense, naming the files. Example: `Read exceptions.py and replaced it by exceptions.hpp.` Do not write plans or a list of everything done so far: the tree already shows what is `visited` and what is `pending`.
|
|
135
|
+
- `actions` is an ordered list with at least one item. Each item is one separate action call, so you may send several in one reply. They run in the order you list them. Grouping is allowed, for example several `read` calls, or `save` followed by `update_status`.
|
|
136
|
+
|
|
137
|
+
| name | arg | what it does |
|
|
138
|
+
|---|---|---|
|
|
139
|
+
| `read` | `"path"` (a string, never a list) | Returns the full text of the file. |
|
|
140
|
+
| `save` | `["path", "content"]` | Creates a NEW file with this content, creating missing folders. |
|
|
141
|
+
| `update` | `["path", "new_path", "new_content"]` | Replaces the content of an existing file and renames it to `new_path`. This is how a `.py` becomes a `.cpp`. |
|
|
142
|
+
| `update_status` | `["path", "status"]` | Sets the status of a file in the tree. `status` is `"visited"` or `"pending"`. |
|
|
143
|
+
| `quit` | do NOT include the `arg` key | Ends the loop. |
|
|
144
|
+
|
|
145
|
+
Rules for `arg`:
|
|
146
|
+
|
|
147
|
+
- When an action has more than one value, `arg` is a JSON list with the values in EXACTLY the order shown above.
|
|
148
|
+
- `content` in `save` and `new_content` in `update` are the COMPLETE file, never a diff or a snippet. Anything you omit is lost.
|
|
149
|
+
- Text is written exactly as you send it. Escape double quotes (`\"`), backslashes (`\\`) and line breaks (`\n`) inside JSON strings. Tabs are `\t`.
|
|
150
|
+
- `quit` must be the last action of the list and should be sent alone, once everything is done.
|
|
151
|
+
|
|
152
|
+
## Examples
|
|
153
|
+
|
|
154
|
+
IMPORTANT: the paths and code below are fictional. Never copy them. Always take paths from `PENDING FILES` and the code from the file you read.
|
|
155
|
+
|
|
156
|
+
Read two files:
|
|
157
|
+
|
|
158
|
+
{"actions": [{"name": "read", "arg": "<path A from PENDING FILES>"}, {"name": "read", "arg": "<path B from PENDING FILES>"}], "content": "Read A and B to port them."}
|
|
159
|
+
|
|
160
|
+
Replace a Python file by its C++ version (status first, then the rename). The new content is the port of the code you just read:
|
|
161
|
+
|
|
162
|
+
{"actions": [{"name": "update_status", "arg": ["<path A>.py", "visited"]}, {"name": "update", "arg": ["<path A>.py", "<path A>.hpp", "<complete C++ port of the code you read>"]}], "content": "Replaced <path A>.py by <path A>.hpp."}
|
|
163
|
+
|
|
164
|
+
Replace a file that needs a header and a source (the `.cpp` via `update`, the `.hpp` via `save`):
|
|
165
|
+
|
|
166
|
+
{"actions": [{"name": "update_status", "arg": ["<path B>.py", "visited"]}, {"name": "save", "arg": ["<path B>.hpp", "<complete header>"]}, {"name": "update", "arg": ["<path B>.py", "<path B>.cpp", "<complete source>"]}], "content": "Replaced <path B>.py by <path B>.hpp and <path B>.cpp."}
|
|
167
|
+
|
|
168
|
+
Skip a file that is not code:
|
|
169
|
+
|
|
170
|
+
{"actions": [{"name": "update_status", "arg": ["<path of the README>", "visited"]}], "content": "The README is not code, marked it visited without changes."}
|
|
171
|
+
|
|
172
|
+
Finish (only when `PENDING FILES` has no `.py` left):
|
|
173
|
+
|
|
174
|
+
{"actions": [{"name": "save", "arg": ["CMakeLists.txt", "<complete CMakeLists.txt>"]}, {"name": "quit"}], "content": "Saved CMakeLists.txt and finished the migration."}
|
|
File without changes
|
_codeshift/schema.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
from pydantic import BaseModel, Field
|
|
2
|
+
from typing import Literal
|
|
3
|
+
|
|
4
|
+
class ModelConfig(BaseModel):
|
|
5
|
+
|
|
6
|
+
name: Literal[
|
|
7
|
+
"Qwen/Qwen3-Coder-Next",
|
|
8
|
+
"Qwen/Qwen2.5-Coder-14B-Instruct",
|
|
9
|
+
"Qwen/Qwen2.5-Coder-7B-Instruct",
|
|
10
|
+
"Qwen/Qwen2.5-Coder-3B-Instruct",
|
|
11
|
+
] = Field(default="Qwen/Qwen2.5-Coder-14B-Instruct")
|
|
12
|
+
temperature: float = Field(default=0.5)
|
|
13
|
+
|
|
14
|
+
class AppConfig(BaseModel):
|
|
15
|
+
|
|
16
|
+
model: ModelConfig
|
|
17
|
+
path: str|None = Field(default=None)
|
|
18
|
+
env_file: str = Field(default=".env")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class ActionMapping(BaseModel):
|
|
22
|
+
|
|
23
|
+
name: Literal["save", "quit", "read", "update_status", "update"]
|
|
24
|
+
arg: str | list[str] | None = Field(default=None)
|
|
25
|
+
|
|
26
|
+
class OutPutMapping(BaseModel):
|
|
27
|
+
actions: list[ActionMapping]
|
|
28
|
+
content: str
|
|
29
|
+
|
|
30
|
+
|
|
File without changes
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
|
|
2
|
+
import os
|
|
3
|
+
from _codeshift.logs import logger
|
|
4
|
+
from _codeshift.schema import AppConfig
|
|
5
|
+
from _codeshift.color import Color
|
|
6
|
+
from _codeshift import ui
|
|
7
|
+
from _codeshift.utils.file import FileControl
|
|
8
|
+
from _codeshift.exceptions import ModelNotFound, TemperatureError, PathNotFound, NotFoundEnv
|
|
9
|
+
from dotenv import load_dotenv
|
|
10
|
+
DEFAULT_ENV_FILE = ".env"
|
|
11
|
+
|
|
12
|
+
AVAILABLE_MODELS = [
|
|
13
|
+
"Qwen/Qwen3-Coder-Next",
|
|
14
|
+
"Qwen/Qwen2.5-Coder-14B-Instruct",
|
|
15
|
+
"Qwen/Qwen2.5-Coder-7B-Instruct",
|
|
16
|
+
"Qwen/Qwen2.5-Coder-3B-Instruct",
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
class Settings(FileControl):
|
|
20
|
+
|
|
21
|
+
def __init__(self)->None:
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
self.color = Color()
|
|
25
|
+
|
|
26
|
+
def _header(self, title: str) -> None:
|
|
27
|
+
ui.header(title)
|
|
28
|
+
|
|
29
|
+
def _prompt(self, text: str, hint: str = "") -> str:
|
|
30
|
+
return ui.prompt(text, hint)
|
|
31
|
+
|
|
32
|
+
def get_config(self) -> dict:
|
|
33
|
+
|
|
34
|
+
self.file = self.read(".codeshift/config.json")
|
|
35
|
+
|
|
36
|
+
return AppConfig.model_validate(self.file).model_dump()
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def set_settings(self) -> None:
|
|
40
|
+
|
|
41
|
+
data= {}
|
|
42
|
+
|
|
43
|
+
self._header("⚙ Configuração do CodeShift")
|
|
44
|
+
print(f"\n{self.color.bold(self.color.blue('Modelos disponíveis:'))}")
|
|
45
|
+
MODELS = AVAILABLE_MODELS
|
|
46
|
+
|
|
47
|
+
for number in range(len(MODELS)):
|
|
48
|
+
print(f" {self.color.yellow(f'[{number}]')} {self.color.green(MODELS[number])}")
|
|
49
|
+
print()
|
|
50
|
+
|
|
51
|
+
model = input(self._prompt("Digite o número do modelo"))
|
|
52
|
+
model = int(model)
|
|
53
|
+
|
|
54
|
+
temperature = float(input(self._prompt("Escolha uma temperatura", "0.2 a 0.9")))
|
|
55
|
+
|
|
56
|
+
if model > len(MODELS) -1:
|
|
57
|
+
raise ModelNotFound(f"Not found model")
|
|
58
|
+
|
|
59
|
+
if 0.2 > temperature or temperature > 0.9:
|
|
60
|
+
raise TemperatureError(f"Invalid temperature {temperature}")
|
|
61
|
+
|
|
62
|
+
data["model"] = {
|
|
63
|
+
"name": MODELS[model],
|
|
64
|
+
"temperature": temperature
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
env_file = input(self._prompt("Caminho do arquivo .env", "opcional, Enter para pular")).strip()
|
|
68
|
+
|
|
69
|
+
if env_file:
|
|
70
|
+
env_file = os.path.abspath(os.path.expanduser(env_file))
|
|
71
|
+
|
|
72
|
+
if not os.path.isfile(env_file):
|
|
73
|
+
raise PathNotFound(f"Not found env file {env_file}")
|
|
74
|
+
|
|
75
|
+
data["env_file"] = env_file
|
|
76
|
+
else:
|
|
77
|
+
data["env_file"] = DEFAULT_ENV_FILE
|
|
78
|
+
|
|
79
|
+
self.save(".codeshift/config.json", data)
|
|
80
|
+
|
|
81
|
+
print(self.color.green(f"\n✔ Configurações salvas em {self.color.bold(os.path.abspath('.codeshift/config.json'))}"))
|
|
82
|
+
logger.success(f"Settings saved with success")
|
|
83
|
+
|
|
84
|
+
def update_settings(self) -> None:
|
|
85
|
+
data = self.get_config()
|
|
86
|
+
models = AVAILABLE_MODELS
|
|
87
|
+
|
|
88
|
+
self._header("✎ Atualizar configurações")
|
|
89
|
+
|
|
90
|
+
while True:
|
|
91
|
+
option = input(
|
|
92
|
+
f"\n{self.color.bold('Configurações do Modelo')} "
|
|
93
|
+
f"({self.color.yellow('name')}, {self.color.yellow('temperature')}, {self.color.red('exit')})\n"
|
|
94
|
+
+ self._prompt("Qual você deseja alterar")
|
|
95
|
+
).strip().lower()
|
|
96
|
+
|
|
97
|
+
if option == "exit":
|
|
98
|
+
break
|
|
99
|
+
|
|
100
|
+
match option:
|
|
101
|
+
case "name":
|
|
102
|
+
print(f"\n{self.color.bold(self.color.blue('Modelos disponíveis:'))}")
|
|
103
|
+
for idx, m in enumerate(models, start=1):
|
|
104
|
+
print(f" {self.color.yellow(f'[{idx}]')} {self.color.green(m)}")
|
|
105
|
+
|
|
106
|
+
choice = input("\n" + self._prompt("Digite o número do modelo")).strip()
|
|
107
|
+
|
|
108
|
+
if not choice.isdigit() or not (1 <= int(choice) <= len(models)):
|
|
109
|
+
raise ModelNotFound(f"Not found model index {choice}")
|
|
110
|
+
|
|
111
|
+
selected_model = models[int(choice) - 1]
|
|
112
|
+
data["model"]["name"] = selected_model
|
|
113
|
+
print(self.color.green(f"✔ Modelo alterado para {self.color.bold(selected_model)}"))
|
|
114
|
+
break
|
|
115
|
+
|
|
116
|
+
case "temperature":
|
|
117
|
+
temperature = float(input(self._prompt("Digite uma temperatura", "0.2 a 0.9")))
|
|
118
|
+
|
|
119
|
+
if not (0.2 <= temperature <= 0.9):
|
|
120
|
+
raise TemperatureError(f"Invalid temperature {temperature}")
|
|
121
|
+
|
|
122
|
+
data["model"]["temperature"] = temperature
|
|
123
|
+
print(self.color.green(f"✔ Temperatura alterada para {self.color.bold(temperature)}"))
|
|
124
|
+
break
|
|
125
|
+
|
|
126
|
+
case _:
|
|
127
|
+
print(self.color.red("✘ Não existe essa opção."))
|
|
128
|
+
|
|
129
|
+
self.save(".codeshift/config.json", data)
|
|
130
|
+
|
|
131
|
+
logger.success(f"Saved with success")
|
|
132
|
+
|
|
133
|
+
return data
|
|
134
|
+
|
|
135
|
+
def get_envs(self) -> dict:
|
|
136
|
+
|
|
137
|
+
NAMES = ["url", "api_key"]
|
|
138
|
+
|
|
139
|
+
data = self.get_config()
|
|
140
|
+
envs = {}
|
|
141
|
+
load_dotenv(data.get("env_file") or DEFAULT_ENV_FILE)
|
|
142
|
+
|
|
143
|
+
for name in NAMES:
|
|
144
|
+
|
|
145
|
+
envs[name] = os.getenv(name)
|
|
146
|
+
|
|
147
|
+
return envs
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
|
_codeshift/ui.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import re
|
|
2
|
+
import shutil
|
|
3
|
+
|
|
4
|
+
RESET = "\033[0m"
|
|
5
|
+
_ANSI = re.compile(r"\033\[[0-9;]*m")
|
|
6
|
+
|
|
7
|
+
# Paleta (RGB)
|
|
8
|
+
ORANGE = (217, 119, 87)
|
|
9
|
+
PURPLE = (167, 139, 250)
|
|
10
|
+
CYAN = (103, 232, 249)
|
|
11
|
+
BLUE = (147, 197, 253)
|
|
12
|
+
GREEN = (134, 239, 172)
|
|
13
|
+
YELLOW = (253, 224, 71)
|
|
14
|
+
RED = (252, 165, 165)
|
|
15
|
+
GRAY = (113, 113, 122)
|
|
16
|
+
DARK = (28, 28, 36)
|
|
17
|
+
|
|
18
|
+
MIN_WIDTH, MAX_WIDTH = 50, 78
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def fg(text, color: tuple[int, int, int], bold: bool = False) -> str:
|
|
22
|
+
weight = "\033[1m" if bold else ""
|
|
23
|
+
return f"{weight}\033[38;2;{color[0]};{color[1]};{color[2]}m{text}{RESET}"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def badge(text, color: tuple[int, int, int]) -> str:
|
|
27
|
+
"""Texto escuro sobre fundo colorido, como um botão."""
|
|
28
|
+
return f"\033[48;2;{color[0]};{color[1]};{color[2]}m\033[38;2;{DARK[0]};{DARK[1]};{DARK[2]}m\033[1m {text} {RESET}"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def gradient(text: str, start: tuple[int, int, int], end: tuple[int, int, int], bold: bool = True) -> str:
|
|
32
|
+
"""Pinta cada letra numa cor entre start e end."""
|
|
33
|
+
size = max(len(text) - 1, 1)
|
|
34
|
+
out = []
|
|
35
|
+
for i, char in enumerate(text):
|
|
36
|
+
color = tuple(round(start[k] + (end[k] - start[k]) * i / size) for k in range(3))
|
|
37
|
+
out.append(fg(char, color, bold))
|
|
38
|
+
return "".join(out)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def vlen(text: str) -> int:
|
|
42
|
+
return len(_ANSI.sub("", text))
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def pad(text: str, size: int) -> str:
|
|
46
|
+
return text + " " * max(size - vlen(text), 0)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def width() -> int:
|
|
50
|
+
return max(MIN_WIDTH, min(shutil.get_terminal_size((80, 24)).columns, MAX_WIDTH))
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def box(lines: list[str], title: str = "", color: tuple[int, int, int] = PURPLE) -> str:
|
|
54
|
+
"""Caixa com cantos arredondados. Cada item de `lines` é uma linha (pode ter cor)."""
|
|
55
|
+
inner = width() - 4
|
|
56
|
+
border = lambda s: fg(s, color)
|
|
57
|
+
|
|
58
|
+
if title:
|
|
59
|
+
label = f" {title} "
|
|
60
|
+
top = border("╭─") + fg(label, color, bold=True) + border("─" * (inner + 1 - vlen(label)) + "╮")
|
|
61
|
+
else:
|
|
62
|
+
top = border("╭" + "─" * (inner + 2) + "╮")
|
|
63
|
+
|
|
64
|
+
rows = [f"{border('│')} {pad(line, inner)} {border('│')}" for line in lines]
|
|
65
|
+
bottom = border("╰" + "─" * (inner + 2) + "╯")
|
|
66
|
+
return "\n".join([top, *rows, bottom])
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def header(title: str) -> None:
|
|
70
|
+
line = fg("━" * width(), PURPLE)
|
|
71
|
+
print(f"\n{line}\n {gradient(title, CYAN, PURPLE)}\n{line}")
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def prompt(text: str, hint: str = "") -> str:
|
|
75
|
+
hint_str = f" {fg('(' + hint + ')', GRAY)}" if hint else ""
|
|
76
|
+
return f"{fg('❯', ORANGE, bold=True)} {fg(text, (228, 228, 231), bold=True)}{hint_str}{fg(':', ORANGE)} "
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def ok(text: str) -> None:
|
|
80
|
+
print(f"{fg('✔', GREEN, bold=True)} {fg(text, GREEN)}")
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def warn(text: str) -> None:
|
|
84
|
+
print(f"{fg('▲', YELLOW, bold=True)} {fg(text, YELLOW)}")
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def error(text: str) -> None:
|
|
88
|
+
print(f"{fg('✖', RED, bold=True)} {fg(text, RED)}")
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def info(text: str) -> None:
|
|
92
|
+
print(f"{fg('•', GRAY)} {text}")
|
|
File without changes
|
_codeshift/utils/file.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import os
|
|
3
|
+
from _codeshift.logs import logger
|
|
4
|
+
from typing import Literal, Any
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class FileControl:
|
|
8
|
+
"""Lê e salva arquivos no caminho exato recebido (relativo à pasta onde o comando roda)."""
|
|
9
|
+
|
|
10
|
+
@staticmethod
|
|
11
|
+
def read(path: str, type: Literal["json", "txt"] = "json") -> Any:
|
|
12
|
+
|
|
13
|
+
logger.info(f"Reading {path}...")
|
|
14
|
+
|
|
15
|
+
if not os.path.exists(path):
|
|
16
|
+
raise FileNotFoundError(f"not exists {path}")
|
|
17
|
+
|
|
18
|
+
with open(path, "r", encoding="utf-8") as file:
|
|
19
|
+
|
|
20
|
+
logger.success("Read with success")
|
|
21
|
+
return json.load(file) if type == "json" else file.read()
|
|
22
|
+
|
|
23
|
+
@staticmethod
|
|
24
|
+
def save(path: str, data: Any, type: Literal["json", "txt"] = "json") -> None:
|
|
25
|
+
|
|
26
|
+
folder = os.path.dirname(path)
|
|
27
|
+
if folder:
|
|
28
|
+
os.makedirs(folder, exist_ok=True)
|
|
29
|
+
|
|
30
|
+
logger.info(f"Saving {path}...")
|
|
31
|
+
|
|
32
|
+
with open(path, "w", encoding="utf-8") as file:
|
|
33
|
+
|
|
34
|
+
json.dump(data, file, ensure_ascii=False, indent=4) if type == "json" else file.write(data)
|
|
35
|
+
|
|
36
|
+
logger.success("Saved with success")
|
|
37
|
+
|
|
38
|
+
@staticmethod
|
|
39
|
+
def update(path: str, new_path:str, content:str) -> None:
|
|
40
|
+
|
|
41
|
+
if not os.path.exists(path):
|
|
42
|
+
raise FileNotFoundError(f"Not exists {path}")
|
|
43
|
+
|
|
44
|
+
logger.info(f"Updating {path}...")
|
|
45
|
+
|
|
46
|
+
os.rename(path, new_path)
|
|
47
|
+
|
|
48
|
+
with open(new_path, "w", encoding="utf-8") as f:
|
|
49
|
+
|
|
50
|
+
f.write(content)
|
|
51
|
+
|
|
52
|
+
logger.success(f"{path} updated with success")
|