Skip to content

Instantly share code, notes, and snippets.

@costa86
Last active February 19, 2023 20:39
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save costa86/f64890f4bfa8cf5632137ac9fe9773aa to your computer and use it in GitHub Desktop.
Gist CLI
import requests
import json
from tabulate import tabulate
import questionary
import webbrowser
API_ENDPOINT = "https://api.github.com/gists"
AUTH_TOKEN = ""
USERNAME = ""
def delete_gist(url:str):
headers = {"Authorization": f"token {AUTH_TOKEN}"}
response = requests.delete(url, headers=headers)
print("Gist deleted" if response.status_code == 204 else "Could not delete Gist")
def list_gists():
response = requests.get(f"https://api.github.com/users/{USERNAME}/gists")
choices = ['Delete','Visit']
if response.status_code == 200:
gists = response.json()
all_gists_description = [i['description'] for i in gists]
all_gists_description.sort()
print(f'{len(all_gists_description)} Gists found')
selected_gist_description = questionary.select("Pick a Gist",all_gists_description).ask()
selected_gist = list(filter(lambda x:x['description'] == selected_gist_description,gists))[0]
action = questionary.select('What would you like to do with this Gist?',choices=choices).ask()
match action:
case 'Delete':
confirmation = questionary.confirm('Are you sure you want to delete this Gist?').ask()
if confirmation:
delete_gist(selected_gist['url'])
case 'Visit':
webbrowser.open(selected_gist['html_url'])
return
print(f"Error {response.status_code}: {response.content}")
def create_gist(file_name: str, content: str, description: str):
gist_data = {
"description": description,
"public": True,
"files": {file_name: {"content": content}},
}
json_data = json.dumps(gist_data)
headers = {
"Accept": "application/vnd.github+json",
"Authorization": f"Bearer {AUTH_TOKEN}",
"Content-Type": "application/json",
"X-GitHub-Api-Version": "2022-11-28",
}
response = requests.post(API_ENDPOINT, headers=headers, data=json_data)
result = f'New Gist created: {response.json()["html_url"]}' if response.status_code == 201 \
else f"Status code: {response.status_code}\nText: {response.text}"
print(result)
def get_file_content(file_name: str):
with open(file_name) as f:
return f.read()
def create_gist_wrapper():
file_name = input("File name: ")
content = get_file_content(input("File path: "))
description = input("Description: ")
create_gist(file_name, content, description)
actions = [
("Show Gists", list_gists),
("Create new Gist", create_gist_wrapper)
]
action_labels = [i[0] for i in actions]
action = questionary.select('Pick an option',choices=action_labels).ask()
selected_action = list(filter(lambda x: x[0] == action, actions))[0]
selected_action[1]()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment