Skip to content

Commit

Permalink
Get OS and prefill shell with user commands (#42)
Browse files Browse the repository at this point in the history
- [X] Append command to user bash history and prefill shell. Even though
we can append command to bash history, it does not show up in the
reverse-i-search without sourcing the shell. This is because the child
process cannot modify the environment of the parent caller process
[stack-overflow
reference](https://stackoverflow.com/questions/3661566/python-source-home-bashrc-with-os-system).
So, instead will will pre-fill the shell command with the selected
command.
- [X] Get OS environment
- [X] Refactor unique ID generation - mostly cosmetic 
- [x] Update server to route LLM based on os environment
- [x] Test on Ubuntu Linux
- [x] Test on Darwin (Mac OS)
- [ ] Test on WSL
- [ ] Test on Windows Powershell

Thoughts, suggestions, and reviews welcome!

Relevant to #39 and #12
  • Loading branch information
ShishirPatil committed Oct 19, 2023
1 parent d566ac3 commit 386153a
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 43 deletions.
116 changes: 74 additions & 42 deletions go_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,17 @@
import os
import sys
import uuid
import fcntl
import platform
import requests
import subprocess
import termios
import urllib.parse
import sys
from halo import Halo
import go_questionary

__version__ = "0.0.10" # current version
__version__ = "0.0.11" # current version
SERVER_URL = "https://cli.gorilla-llm.com"
UPDATE_CHECK_FILE = os.path.expanduser("~/.gorilla-cli-last-update-check")
USERID_FILE = os.path.expanduser("~/.gorilla-cli-userid")
Expand All @@ -45,6 +48,55 @@
===***==="""


def generate_random_uid():
return str(uuid.uuid4())

def get_git_email():
return subprocess.check_output(["git", "config", "--global", "user.email"]).decode("utf-8").strip()

def get_system_info():
return platform.system()

def write_uid_to_file(uid):
with open(USERID_FILE, "w") as f:
f.write(uid)

def append_to_bash_history(selected_command):
try:
with open(os.path.expanduser("~/.bash_history"), "a") as history_file:
history_file.write(selected_command + '\n')
except Exception as e:
pass




def prefill_shell_cmd(cmd):
# Inspired from
stdin = 0
# Save TTY attributes for stdin
oldattr = termios.tcgetattr(stdin)
# Create new attributes to fake input
newattr = termios.tcgetattr(stdin)
# Disable echo in stdin -> only inject cmd in stdin queue (with TIOCSTI)
newattr[3] &= ~termios.ECHO
# Enable non-canonical mode -> ignore special editing characters
newattr[3] &= ~termios.ICANON
# Use the new attributes
termios.tcsetattr(stdin, termios.TCSANOW, newattr)
# Write the selected command in stdin queue
for c in cmd:
fcntl.ioctl(stdin, termios.TIOCSTI, c)
# Restore TTY attributes for stdin
termios.tcsetattr(stdin, termios.TCSADRAIN, oldattr)


def raise_issue(title, body):
issue_title = urllib.parse.quote(title)
issue_body = urllib.parse.quote(body)
issue_url = f"{ISSUE_URL}?title={issue_title}&body={issue_body}"
print(f"If the problem persists, please raise an issue: {issue_url}")

def check_for_updates():
# Check if a new version of gorilla-cli is available once a day
try:
Expand Down Expand Up @@ -76,56 +128,30 @@ def get_user_id():
# limit increases for your GitHub handle, please raise an issue.
try:
with open(USERID_FILE, "r") as f:
user_id = str(f.read())
# If file found and user_id is blank. User hasn't setup github
if user_id == "":
user_id = str(uuid.uuid4())
user_id = f.read().strip()
if not user_id:
user_id = generate_random_uid()
return user_id
except FileNotFoundError:
# First time
try:
user_id = (
subprocess.check_output(["git", "config", "--global", "user.email"])
.decode("utf-8")
.strip()
)
user_id = get_git_email()
print(WELCOME_TEXT)
response = (
input(f"Use your Github handle ({user_id}) as user id? [Y/n]: ")
.strip()
.lower()
)
response = input(f"Use your Github handle ({user_id}) as user id? [Y/n]: ").strip().lower()
if response in ["n", "no"]:
user_id = str(uuid.uuid4())
user_id = generate_random_uid()
except Exception as e:
# If git not installed then generate and use a random user id
issue_title = urllib.parse.quote(
f"Problem with generating userid from GitHub: {str(e)}"
)
issue_body = urllib.parse.quote(f"Unable to generate userid: {str(e)}")
print(
f"Git not installed, so cannot import userid from Git. \n Please run 'gorilla <command>' again after initializing git. \n Will use a random user-id. If the problem persists, please raise an issue: \
{ISSUE_URL}?title={issue_title}&body={issue_body}"
)
user_id = str(uuid.uuid4())
print(f"Git not installed. Unable to import userid from Git.")
print(f"Will use a random user-id.")
user_id = generate_random_uid()
print(WELCOME_TEXT)

try:
# Write user_id to file
with open(USERID_FILE, "w") as f:
f.write(user_id)
write_uid_to_file(user_id)
return user_id
except Exception as e:
issue_title = urllib.parse.quote("Problem with userid file")
issue_body = urllib.parse.quote(f"Unable to write userid file: {str(e)}")
print("Unable to write userid to file:", e)
print(
f"Try deleting USERID_FILE and run 'gorilla <command>' again. If the problem persists, please raise an issue:\
{ISSUE_URL}?title={issue_title}&body={issue_body}"
)
print(
f"Using a temporary UID {user_id} for now.."
)
print(f"Unable to write userid to file: {e}")
raise_issue("Problem with userid file", f"Unable to write userid file: {e}")
print(f"Using a temporary UID {user_id} for now.")
return user_id


Expand All @@ -141,6 +167,7 @@ def execute_command(cmd):
args = sys.argv[1:]
user_input = " ".join(args)
user_id = get_user_id()
system_info = get_system_info()

# Generate a unique interaction ID
interaction_id = str(uuid.uuid4())
Expand All @@ -151,9 +178,10 @@ def execute_command(cmd):
"user_id": user_id,
"user_input": user_input,
"interaction_id": interaction_id,
"system_info": system_info,
}
response = requests.post(
f"{SERVER_URL}/commands", json=data_json, timeout=30
f"{SERVER_URL}/commands_v2", json=data_json, timeout=30
)
commands = response.json()
except requests.exceptions.RequestException as e:
Expand All @@ -172,6 +200,11 @@ def execute_command(cmd):
# happens when Ctrl-C is pressed
return
exit_condition = execute_command(selected_command)

# Append command to bash history
if system_info == "Linux":
append_to_bash_history(selected_command)
prefill_shell_cmd(selected_command)

# Commands failed / succeeded?
try:
Expand All @@ -190,6 +223,5 @@ def execute_command(cmd):
except requests.exceptions.Timeout:
print("Failed to send command execution result to the server: Timeout.")


if __name__ == "__main__":
main()
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

setup(
name="gorilla-cli",
version="0.0.10",
version="0.0.11",
url="https://github.com/gorilla-llm/gorilla-cli",
author="Shishir Patil, Tianjun Zhang",
author_email="[email protected], [email protected]",
Expand Down

0 comments on commit 386153a

Please sign in to comment.