Skip to content

Commit

Permalink
feat: add copiable variable
Browse files Browse the repository at this point in the history
  • Loading branch information
0xbrayo committed Nov 1, 2024
1 parent 9fbe823 commit c3631b6
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 7 deletions.
2 changes: 1 addition & 1 deletion gptme/tools/shell.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ def execute_shell(
break

if not allowlisted:
print_preview(cmd, "bash")
print_preview(cmd, "bash", True)
if not confirm("Run command?"):
yield Message("system", "User chose not to run command.")
return
Expand Down
2 changes: 1 addition & 1 deletion gptme/tools/tmux.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ def execute_tmux(
assert not args
cmd = code.strip()

print_preview(f"Command: {cmd}", "bash")
print_preview(f"Command: {cmd}", "bash", copy=True)
if not confirm(f"Execute command: {cmd}?"):
yield Message("system", "Command execution cancelled.")
return
Expand Down
32 changes: 27 additions & 5 deletions gptme/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,10 +135,27 @@ def epoch_to_age(epoch, incl_date=False):
)


def print_preview(code: str, lang: str): # pragma: no cover
copiable = False


def set_copiable():
global copiable
copiable = True


def clear_copiable():
global copiable
copiable = False


def print_preview(code: str, lang: str, copy: bool = False): # pragma: no cover
print()
print("[bold white]Preview[/bold white]")
set_copytext(code)

if copy:
set_copiable()
set_copytext(code)

# NOTE: we can set background_color="default" to remove background
print(Syntax(code.strip("\n"), lang))
print()
Expand All @@ -152,13 +169,14 @@ def ask_execute(question="Execute code?", default=True) -> bool: # pragma: no c
termios.tcflush(sys.stdin, termios.TCIFLUSH) # flush stdin

choicestr = f"[{'Y' if default else 'y'}/{'n' if default else 'N'}]"
copystr = "ctrk-c to copy"
copystr = "ctrl-c to copy"
console.print(
f"[bold bright_yellow on red] {question} {choicestr} {copystr} [/] ",
f"[bold bright_yellow on red] {question} {choicestr} {copystr if copiable else ''} [/] ",
end="",
)
print()
answer = listen_for_character()
if answer == "\x03":
if copiable and answer == "\x03":
if copy():
print("Copied to clipboard.")
return False
Expand Down Expand Up @@ -329,8 +347,12 @@ def listen_for_character():
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
if ch in ("\n", "\r"):
# handle enter key
ch = ""
except KeyboardInterrupt:
ch = "\x03" # ASCII code for Ctrl+C
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
clear_copiable()
return ch

0 comments on commit c3631b6

Please sign in to comment.