|
#!/usr/bin/env python |
|
|
|
# See https://www.btbytes.com/posts/2020-05-14-4-notes.html |
|
# Pradeep Gowda, 2023-03-21 |
|
# TODO: Updating a secret gist to be public does not work yet |
|
|
|
import os |
|
import argparse |
|
import json |
|
import urllib.request |
|
|
|
API_URL = "https://api.github.com/gists" |
|
|
|
ACCESS_TOKEN = os.getenv("GITHUB_TOKEN") |
|
|
|
|
|
def create_gist(files, public): |
|
"""Create a new gist with the given files.""" |
|
data = {"description": "Gist created by gitstash", "public": public, "files": {}} |
|
|
|
for file_path in files: |
|
with open(file_path, "r") as file: |
|
content = file.read() |
|
file_name = os.path.basename(file_path) |
|
data["files"][file_name] = {"content": content} |
|
|
|
headers = { |
|
"Authorization": f"token {ACCESS_TOKEN}", |
|
"Accept": "application/vnd.github.v3+json", |
|
} |
|
|
|
data = json.dumps(data).encode("utf-8") |
|
|
|
req = urllib.request.Request(API_URL, data=data, headers=headers, method="POST") |
|
|
|
try: |
|
with urllib.request.urlopen(req) as response: |
|
response_data = json.loads(response.read().decode("utf-8")) |
|
gist_url = response_data["html_url"] |
|
print(f"Gist created: {gist_url}") |
|
except urllib.error.HTTPError as e: |
|
print("Failed to create gist.") |
|
print(e.read().decode("utf-8")) |
|
|
|
|
|
def update_gist(files, gist_id): |
|
"""Update an existing gist with the given files.""" |
|
url = f"{API_URL}/{gist_id}" |
|
|
|
data = {"files": {}} |
|
|
|
for file_path in files: |
|
with open(file_path, "r") as file: |
|
content = file.read() |
|
file_name = os.path.basename(file_path) |
|
data["files"][file_name] = {"content": content} |
|
|
|
headers = { |
|
"Authorization": f"token {ACCESS_TOKEN}", |
|
"Accept": "application/vnd.github.v3+json", |
|
} |
|
|
|
data = json.dumps(data).encode("utf-8") |
|
|
|
req = urllib.request.Request(url, data=data, headers=headers, method="PATCH") |
|
|
|
try: |
|
with urllib.request.urlopen(req) as response: |
|
print("Gist updated successfully.") |
|
except urllib.error.HTTPError as e: |
|
print("Failed to update gist.") |
|
print(e.read().decode("utf-8")) |
|
|
|
|
|
def main(): |
|
parser = argparse.ArgumentParser(description="Store files in a GitHub gist.") |
|
parser.add_argument( |
|
"files", metavar="FILE", nargs="+", help="Files to store in the gist." |
|
) |
|
parser.add_argument("--gist-id", help="ID of the gist to update.") |
|
parser.add_argument( |
|
"--public", action="store_true", help="Make the gist public (default: private)." |
|
) |
|
|
|
args = parser.parse_args() |
|
|
|
if args.gist_id: |
|
update_gist(args.files, args.gist_id) |
|
else: |
|
create_gist(args.files, args.public) |
|
|
|
|
|
if __name__ == "__main__": |
|
main() |