-
-
Notifications
You must be signed in to change notification settings - Fork 807
/
Copy pathutils.py
76 lines (64 loc) · 2.24 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import os
import platform
import shlex
from tempfile import NamedTemporaryFile
from typing import Any, Callable
import typer
from click import BadParameter
def get_edited_prompt() -> str:
"""
Opens the user's default editor to let them
input a prompt, and returns the edited text.
:return: String prompt.
"""
with NamedTemporaryFile(suffix=".txt", delete=False) as file:
# Create file and store path.
file_path = file.name
editor = os.environ.get("EDITOR", "vim")
# This will write text to file using $EDITOR.
os.system(f"{editor} {file_path}")
# Read file when editor is closed.
with open(file_path, "r", encoding="utf-8") as file:
output = file.read()
os.remove(file_path)
if not output:
raise BadParameter("Couldn't get valid PROMPT from $EDITOR")
return output
def run_command(command: str) -> None:
"""
Runs a command in the user's shell.
It is aware of the current user's $SHELL.
:param command: A shell command to run.
"""
if platform.system() == "Windows":
is_powershell = len(os.getenv("PSModulePath", "").split(os.pathsep)) >= 3
full_command = (
f'powershell.exe -Command "{command}"'
if is_powershell
else f'cmd.exe /c "{command}"'
)
else:
shell = os.environ.get("SHELL", "/bin/sh")
full_command = f"{shell} -c {shlex.quote(command)}"
os.system(full_command)
def option_callback(func: Callable) -> Callable: # type: ignore
def wrapper(cls: Any, value: str) -> None:
if not value:
return
func(cls, value)
raise typer.Exit()
return wrapper
@option_callback
def install_shell_integration(*_args: Any) -> None:
"""
Installs shell integration. Currently only supports Linux.
Allows user to get shell completions in terminal by using hotkey.
Allows user to edit shell command right away in terminal.
"""
# TODO: Add support for Windows.
# TODO: Implement updates.
if platform.system() == "Windows":
typer.echo("Windows is not supported yet.")
else:
url = "https://raw.githubusercontent.com/TheR1D/shell_gpt/shell-integrations/install.sh"
os.system(f'sh -c "$(curl -fsSL {url})"')