import requests
import re


def load_all_resource(url, token):
    """
    Downloads JSON from an API URL. Github paginates when many items are
    present; if a requested URL has multiple pages, this function will request
    all the pages and concatenate the results.
    """
    print(url)
    headers = {
        'Accept': 'application/vnd.github.squirrel-girl-preview+json',
        'Authorization': 'token ' + token,
    }
    r = requests.get(url, headers=headers)
    if not r.ok:
        raise Exception('Github returned status code {} ({}) when loading {}. Check that '
                        'your username, password, and repo name are correct.'.format(r.status_code, r.reason, url))
    data = r.json()
    # Load data from the next pages, if any
    if 'link' in r.headers:
        pages = {rel: url for url, rel in re.findall(r'<(.*?)>;\s+rel=\"(.*?)\"', r.headers['link'])}
        print(pages)
        if 'next' in pages:
            data.extend(load_all_resource(pages['next'], token))
    return data