Skip to content

Instantly share code, notes, and snippets.

@jayvdb
Created August 8, 2014 20:24
Show Gist options
  • Save jayvdb/ac0d1005e772647b0c76 to your computer and use it in GitHub Desktop.
Save jayvdb/ac0d1005e772647b0c76 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
"""
Get a github user's fork of a gist.
Given a starting gist id, traverse the forks to find
a gist for the github username provided in the first
parameter of the command line.
"""
import json
import urllib2
base_url = 'https://api.github.com'
base_gist_id = None
def get_fork_list_data(gist_id):
url = base_url + '/gists/' + gist_id
if gist_id != base_gist_id:
url += '/forks'
rawdata = urllib2.urlopen(url).read()
jsondata = json.loads(rawdata)
return jsondata
def fork_list(gist_id):
origin_gist = get_fork_list_data(gist_id)
yield origin_gist
forks = dict([(fork['id'], fork)
for fork in origin_gist['forks']])
while len(forks):
for fork_gist_id in forks.keys()[:]:
fork_list_data = get_fork_list_data(fork_gist_id)
for record in fork_list_data:
gist_id = record['id']
yield record
forks_url = record['forks_url']
forks[gist_id] = forks_url
del forks[fork_gist_id]
def find_suitable_gist(gen, username):
for gist in gen:
gist_username = gist['owner']['login']
if gist_username == username:
gist_git_url = gist['git_pull_url']
return gist_git_url
def main():
import sys
global base_gist_id
base_gist_id = sys.argv[1]
github_username = sys.argv[2]
gist_url = find_suitable_gist( fork_list( base_gist_id ), github_username)
if gist_url:
print gist_url
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment