Skip to content

Commit 2dec468

Browse files
committed
add json return, improve prompts
1 parent 3b58dd3 commit 2dec468

File tree

5 files changed

+61
-33
lines changed

5 files changed

+61
-33
lines changed

.gitignore

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,4 @@
44
*.resp.json
55
/dist
66
**/__pycache__/**
7-
.oai.txt
7+
.oai

codegpt/files.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,9 @@ def load_text(filenames):
1212
def write_text(files, backup=False):
1313
# If the backup option is specified and the file exists,
1414
# write the existing file to <filename>.bak
15-
for out in files:
16-
filename = out['filename']
15+
for i, out in enumerate(files):
16+
filename = out.get('filename', f"{i}.txt")
17+
typer.secho(f"Hmm, didn't find a filename, writing to {filename}", color=typer.colors.MAGENTA)
1718
if backup and os.path.exists(filename):
1819
with open(filename, "r") as f_in:
1920
with open(f"{filename}.bak", "w") as f_out:

codegpt/gpt_interface.py

Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -33,36 +33,37 @@ def send_iffy_edit(prompt: str, code: Dict[str, str], clipboard: bool = False, y
3333

3434
for filename, code_string in code.items():
3535
if not clipboard:
36-
full_prompt += f"\n\nFile: {filename}\n"
37-
full_prompt += f"```\n{code_string}\n```"
36+
full_prompt += f"\n\nfilename:\n> {filename}\n"
37+
nl = '\n'
38+
full_prompt += f"code:\n{nl.join(f'> {x}' for x in code_string.splitlines())}\n\n"
3839

3940
full_prompt += f"\n\nDo the following: {prompt}"
4041

41-
if not clipboard:
42+
if clipboard:
4243
full_prompt += dedent("""
43-
You MUST output complete files.
4444
45-
For each file you wish to output (only if you modified it or made a new one),
46-
answer in this exact format:
45+
Answer in the following format:
4746
48-
filename:
49-
> <the filename to be output>
5047
explanation:
5148
> <The changes that you made>
5249
code:
53-
> <code line 1>
54-
> <code line 2...>""")
50+
> <the code to be output line 1>
51+
> <the code to be output, line n...>""")
52+
5553
else:
5654
full_prompt += dedent("""
57-
58-
Answer in the following format:
59-
55+
56+
You may only output complete files.
57+
58+
If you add or modify a file, return it in this exact format:
59+
60+
filename:
61+
> <the filename to be output>
6062
explanation:
6163
> <The changes that you made>
6264
code:
63-
> <the code to be output line 1>
64-
> <the code to be output line 2>
65-
> <the code to be output, line n...>""")
65+
> <code line 1>
66+
> <code line n...>""")
6667

6768
max_tokens = confirm_send(full_prompt, yes=yes)
6869

codegpt/main.py

Lines changed: 39 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import os
22
import typer
3+
import json
34

45
from codegpt import prompts
56

@@ -21,23 +22,27 @@ def edit_file(
2122
..., help="Instruction to edit the file(s). Keep it short! Wrap with quotes.",
2223
),
2324
filenames: List[Path] = typer.Argument(
24-
..., help="List of filenames to edit. If not provided, will prompt for input.",
25+
[], help="List of filenames to edit. If not provided, will prompt for input.",
2526
),
2627
backup: bool = typer.Option(
2728
False, "--backup", "-b", help="Whether to create a backup of the original file(s).",
2829
),
2930
yes: bool = typer.Option(False, "--yes", "-y", help="Don't ask for confirmation.",),
31+
raw_code: str = typer.Option(None, "--raw-code", "-c", help="Raw code to edit. Overrides filenames")
3032
):
3133
"""
32-
Edit one or more files using codegpt.
34+
Do something given some code for context. Asking for documents, queries, etc. should work okay. Edits are iffy, but work a lot of the time.
35+
36+
Your code better be in git before you use this.
3337
3438
FILENAMES: list of filenames to edit. If not provided, will prompt for input.
3539
INSTRUCTION: the instruction to edit the file(s). Keep it short!
3640
"""
37-
if not filenames:
38-
filenames = typer.prompt("Enter the filenames to edit, separated by spaces").split()
39-
code = files.load_text(filenames)
40-
result = gpt.send_iffy_edit(instruction, code, yes=yes)
41+
42+
if not filenames and not raw_code:
43+
raise typer.BadParameter("Either FILENAMES or --raw-code (-c) must be provided.")
44+
code = {"code": raw_code} if raw_code else files.load_text(filenames)
45+
result = gpt.send_iffy_edit(instruction, code, yes=yes, clipboard=bool(raw_code))
4146
files.write_text(result, backup)
4247
typer.secho("Done!", color=typer.colors.BRIGHT_BLUE)
4348

@@ -46,28 +51,48 @@ def edit_file(
4651
def quick_edit_file(
4752
option: str = typer.Argument(..., help=f"{{{'|'.join(prompts.prompts.keys())}}}"),
4853
filenames: List[str] = typer.Argument(..., help="Enter the filenames to edit, separated by spaces"),
49-
backup: bool = typer.Option(False, '--backup', '-b', help="Whether to create a backup of the original file(s)."),
54+
backup: bool = typer.Option(
55+
False, "--backup", "-b", help="Whether to create a backup of the original file(s).",
56+
),
57+
yes: bool = typer.Option(False, "--yes", "-y", help="Don't ask for confirmation.",),
58+
raw_code: str = typer.Option(None, "--raw-code", "-c", help="Raw code to edit. Overrides filenames"),
59+
json: bool = typer.Option(False, "--json", "-j", help="Output in JSON format"),
5060
):
5161
"""
52-
Edit a file using codegpt's built in prompts
62+
Edit a file using codegpt's built in prompts.
63+
64+
Arguments for `option`:
65+
- comment - Adds or updates comments
66+
- varnames - Makes variable names reasonable
67+
- ugh - Do anything GPT can to make the code suck less (might break stuff...)
68+
- docs - Generate (or update) docs, including README.md
69+
- bugs - Comment in code where the bugs are if GPT sees them (iffy)
70+
- vulns - Comment in code where the vulns are if GPT sees them (iffy)
5371
"""
5472
if option not in prompts.prompts:
5573
raise typer.BadParameter(f"{option} is not a valid option. Must be one of {list(prompts.prompts.keys())}")
56-
code = files.load_text(filenames)
57-
result = gpt.send_iffy_edit(prompts.prompts[option], code)
74+
75+
if not filenames and not raw_code:
76+
raise typer.BadParameter("Either FILENAMES or --raw-code (-c) must be provided.")
77+
78+
code = {"code": raw_code} if raw_code else files.load_text(filenames)
79+
result = gpt.send_iffy_edit(prompts.prompts[option], code, yes=yes, clipboard=bool(raw_code))
80+
81+
if json:
82+
return json.dumps(result, sort_keys=True, indent=4)
83+
5884
files.write_text(result, backup)
59-
typer.secho("done", color=typer.colors.BRIGHT_BLUE)
85+
typer.secho("Done!", color=typer.colors.BRIGHT_BLUE)
6086

6187

62-
@app.command()
88+
@app.command("config")
6389
def config():
6490
"""
6591
Configuration instructions for the OpenAI secret key for the codegpt CLI.
6692
"""
6793
# check if the secret key is already set in the environment variables
6894
if "OPENAI_SECRET_KEY" in os.environ:
69-
print("The OPENAI_SECRET_KEY is already set in the environment variables.")
70-
return
95+
typer.secho("OPENAI_SECRET_KEY is already set in the environment! You probably don't need this.", typer.colors.BRIGHT_BLUE)
7196
else:
7297
typer.confirm(
7398
"""

codegpt/prompts.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
"comment": "Add or update comments according to the given language's standards. Add or update function, module, or class level comments if they're appropriate.",
33
"varnames": "Change variable names, but nothing else, to make the code more readable. For example, instead of using 'x' and 'y', use 'width' and 'height'.",
44
"ugh": "Do anything you can to make this code more readable. Add comments, change variable and function names, add whitespace, whatever. Add a readme to explain what the code does and where it could be improved.",
5+
"docs": "Generate documentation in markdown format for the given files. Make sure to include a README.md for github. If provided markdown files, update them and use their current structure.",
56
"bugs": """Find any bugs you can, note them in comments prefixed with BUG:
67
78
Before:

0 commit comments

Comments
 (0)