Skip to content

Instantly share code, notes, and snippets.

@oaustegard
Created February 13, 2023 04:26
  • 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 oaustegard/bfa137272759474be13f294f09110175 to your computer and use it in GitHub Desktop.
Clone all Gists
# Clone all gists from an accoun
# Requires PAT with Read/Write Account Permission for Gists, stored in a .env file
# Mostly generated with GitHub CoPilot
# TODO: parameterize storage location and username
import os
import requests
from dotenv import load_dotenv
# create a function for the above behavior buty which also accepts a page number as an argument
def get_gists(username, access_token, per_page=30, page=1):
"""
Get a list of a user's Gists.
Args:
username (str): The GitHub username.
access_token (str): The GitHub personal access token.
per_page (int): The number of results to return per page.
page (int): The page number of results to return.
"""
url= f"https://api.github.com/users/{username}/gists"
headers = {"Authorization": f"token {access_token}"}
params = {"per_page": per_page, "page": page}
response = requests.get(url, headers=headers, params=params)
return response.json()
# Get every gist for a user by iterating over the pages until there are no more results
def get_all_gists(username, access_token):
"""
Get a list of a user's Gists.
Args:
username (str): The GitHub username.
access_token (str): The GitHub personal access token.
"""
gists = []
page = 1
while True:
page_gists = get_gists(username, access_token, page=page)
if page_gists:
gists.extend(page_gists)
page += 1
else:
break
return gists
# Iterate over the list of Gists and clone each one
def clone_gists(gists, clone_dir):
"""
Clone a list of Gists.
Args:
gists (list): A list of Gists.
clone_dir (str): The directory to clone the Gists to.
"""
for gist in gists:
#first check iff the gist is already cloned
if os.path.exists(f"{clone_dir}{gist['id']}"):
print(f"Gist {gist['id']} already cloned")
continue
clone_url = gist["git_pull_url"]
os.system(f"git -C {clone_dir} clone {clone_url}")
#main function
def main():
# Set the path to the directory where you want to clone all your Gists to
clone_dir = "/Users/austegard/Projects/gists/"
# Set your GitHub username and personal access token
username = "oaustegard"
load_dotenv()
# get the access token from the .env file
access_token = os.getenv("GITHUB_ACCESS_TOKEN")
# Get all the Gists for the user
gists = get_all_gists(username, access_token)
# Clone all the Gists
clone_gists(gists, clone_dir)
# call the main function
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment