|
| 1 | +def create_gist(username, platform = 'colab', verbose = 0): |
| 2 | + if platform == 'colab': |
| 3 | + create_gist_colab(username,verbose=verbose) |
| 4 | + else: |
| 5 | + raise Exception("Platform "+platform+' is not supported.') |
| 6 | + |
| 7 | + |
| 8 | + |
| 9 | + |
| 10 | +def create_gist_colab(username,verbose = 0, ENV_PATH=None): |
| 11 | + filename = username + "-actions.txt" |
| 12 | + if ENV_PATH is None: |
| 13 | + ENV_PATH = "/content/drive/MyDrive/secrets/github.env" |
| 14 | + # Install deps |
| 15 | + !pip -q install PyGithub python-dotenv |
| 16 | + |
| 17 | + import os, requests |
| 18 | + from dotenv import load_dotenv |
| 19 | + from github import Github, Auth, InputFileContent |
| 20 | + |
| 21 | + # Load token from Drive .env |
| 22 | + loaded = load_dotenv(ENV_PATH, override=True) |
| 23 | + assert loaded, f"Could not load {ENV_PATH}" |
| 24 | + TOKEN = os.getenv("GITHUB_TOKEN") |
| 25 | + assert TOKEN, "Missing GITHUB_TOKEN in .env" |
| 26 | + |
| 27 | + # (Optional) sanity check: see scopes returned by API headers |
| 28 | + resp = requests.get( |
| 29 | + "https://api.github.com/user", |
| 30 | + headers={"Authorization": f"token {TOKEN}", "Accept": "application/vnd.github+json"}, |
| 31 | + timeout=20, |
| 32 | + ) |
| 33 | + resp.raise_for_status() |
| 34 | + if verbose>0: |
| 35 | + print("Authenticated as:", resp.json().get("login")) |
| 36 | + print("Token scopes (X-OAuth-Scopes):", resp.headers.get("X-OAuth-Scopes")) |
| 37 | + |
| 38 | + # Use new-style auth to avoid deprecation warning |
| 39 | + g = Github(auth=Auth.Token(TOKEN)) |
| 40 | + |
| 41 | + # Create a local file to upload |
| 42 | + FILEPATH = "/content/" + filename |
| 43 | + with open(FILEPATH, "w", encoding="utf-8") as f: |
| 44 | + f.write("hello, world\n") |
| 45 | + |
| 46 | + # Read content |
| 47 | + with open(FILEPATH, "r", encoding="utf-8") as f: |
| 48 | + content = f.read() |
| 49 | + filename = os.path.basename(FILEPATH) |
| 50 | + |
| 51 | + import smtplib |
| 52 | + from email.mime.text import MIMEText |
| 53 | + |
| 54 | + # Create the gist |
| 55 | + DESCRIPTION = "Example gist created from Colab via .env and PyGithub" |
| 56 | + gist = g.get_user().create_gist( |
| 57 | + public=True, |
| 58 | + files={filename: InputFileContent(content)}, |
| 59 | + description=DESCRIPTION, |
| 60 | + ) |
| 61 | + |
| 62 | + print("Gist created!") |
| 63 | + print("Web view:", gist.html_url) |
| 64 | + print("Raw file:", gist.files[filename].raw_url) |
| 65 | + return() |
0 commit comments