27

是否有一个 API 调用或我未能推翻的任何脚本将我的所有 Gist 从 Github 拉到外部 git repo 或只是返回我他们的名字列表?我知道每一个都是一个单独的 git repo,所以我假设我能做的最好的就是获取后者,然后编写脚本将它们全部放到我的本地盒子上。

编辑 1:我知道将 git repos 从一项服务拉到另一项服务,我专门寻找拥有 411 的人来收集我拥有的所有 Gist 的权威列表,无论是私人的还是公共的。我还认为这可能对其他人有用。与其说是迁移,不如说是一种备份策略。. . 各种各样的。

编辑 2:所以,看来这可能是不可能的。我显然没有用谷歌搜索更新的 Github/Gist API。其他 API 调用适用于简单的 curl 命令,但不适用于 Gist 的 v1 API。尽管如此,API 对所有私人和公共 Gists都说 TBD ,所以我认为这会将 cabash 放在整个事情上,除非一个开明的灵魂勾起了一个brotha。

$ curl http://github.com/api/v2/json/repos/show/alharaka
{"repositories":[{"url":"https://github.com/alharaka/babushka","has_wiki":true,"homepage":"http:
... # tons of more output
echo $?
0
$ 

这个不太热。

$ curl https://gist.github.com/api/v1/:format/gists/:alharaka
$ echo $?
0
$

编辑 3:在我被问到之前,我注意到 API 版本控制有所不同;这种“出色的破解”也无济于事。不过还是很酷。

$ curl https://gist.github.com/api/v2/:format/gists/:alharaka # Notice v2 instead of v1
$ echo $?
0
$
4

11 回答 11

22

GitHub API 的第 3 版以非常简单的方式实现了这一点:

https://api.github.com/users/koraktor/gists

为您提供用户所有 Gist 的列表,该列表提供各种 URL,包括各个 Gist 的 API URL,例如

https://api.github.com/gists/921286

请参阅Gists API v3 文档

于 2011-07-17T14:48:40.663 回答
15

nicerobot 脚本的 API v3中有一个改编版本,最初是为 API v1 编写的:

#!/usr/bin/env python
# Clone or update all a user's gists
# curl -ks https://raw.github.com/gist/5466075/gist-backup.py | USER=fedir python
# USER=fedir python gist-backup.py

import json
import urllib
from subprocess import call
from urllib import urlopen
import os
import math
USER = os.environ['USER']

perpage=30.0
userurl = urlopen('https://api.github.com/users/' + USER)
public_gists = json.load(userurl)
gistcount = public_gists['public_gists']
print "Found gists : " + str(gistcount)
pages = int(math.ceil(float(gistcount)/perpage))
print "Found pages : " + str(pages)

f=open('./contents.txt', 'w+')

for page in range(pages):
    pageNumber = str(page + 1)
    print "Processing page number " + pageNumber
    pageUrl = 'https://api.github.com/users/' + USER  + '/gists?page=' + pageNumber + '&per_page=' + str(int(perpage))
    u = urlopen (pageUrl)
    gists = json.load(u)
    startd = os.getcwd()
    for gist in gists:
        gistd = gist['id']
        gistUrl = 'git://gist.github.com/' + gistd + '.git' 
        if os.path.isdir(gistd):
            os.chdir(gistd)
            call(['git', 'pull', gistUrl])
            os.chdir(startd)
        else:
            call(['git', 'clone', gistUrl])
        if gist['description'] == None:
            description = ''
        else:
            description = gist['description'].encode('utf8').replace("\r",' ').replace("\n",' ')
        print >> f, gist['id'], gistUrl, description
于 2013-04-26T09:59:45.993 回答
5

解释 Github 分页的 @Fedir 脚本的一个版本(如果你有几百个要点):

#!/usr/bin/env python
# Clone or update all a user's gists
# curl -ks https://raw.github.com/gist/5466075/gist-backup.py | USER=fedir python
# USER=fedir python gist-backup.py

import json
import urllib
from subprocess import call
from urllib import urlopen
import os
import math
USER = os.environ['USER']

perpage=30.0
userurl = urlopen('https://api.github.com/users/' + USER)
public_gists = json.load(userurl)
gistcount = public_gists['public_gists']
print "Found gists : " + str(gistcount)
pages = int(math.ceil(float(gistcount)/perpage))
print "Found pages : " + str(pages)

f=open('./contents.txt', 'w+')

for page in range(pages):
    pageNumber = str(page + 1)
    print "Processing page number " + pageNumber
    pageUrl = 'https://api.github.com/users/' + USER  + '/gists?page=' + pageNumber + '&per_page=' + str(int(perpage))
    u = urlopen (pageUrl)
    gists = json.load(u)
    startd = os.getcwd()
    for gist in gists:
        gistd = gist['id']
        gistUrl = 'git://gist.github.com/' + gistd + '.git' 
        if os.path.isdir(gistd):
            os.chdir(gistd)
            call(['git', 'pull', gistUrl])
            os.chdir(startd)
        else:
            call(['git', 'clone', gistUrl])
于 2013-07-10T15:01:59.987 回答
4

根据这个答案中的提示,我编写了这个简单的 Python 脚本,它对我有用。

这是非常少的代码,几乎没有任何错误检查,并将所有用户的要点克隆到当前目录中。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Clone all gists of GitHub username given on the command line."""

import subprocess
import sys
import requests

if len(sys.argv) > 1:
    gh_user = sys.argv[1]
else:
    print("Usage: clone-gists.py <GitHub username>")
    sys.exit(1)

req = requests.get('https://api.github.com/users/%s/gists' % gh_user)

for gist in req.json():
    ret = subprocess.call(['git', 'clone', gist['git_pull_url']])
    if ret != 0:
        print("ERROR cloning gist %s. Please check output." % gist['id'])

有关处理更新的版本,请参阅https://gist.github.com/SpotlightKid/042491a9a2987af04a5a

于 2015-12-02T20:18:48.820 回答
3

除了Thomas Traum 的几个答案。现在看来,用户代理是必须的:http: //developer.github.com/v3/#user-agent-required

所以我做了自己的练习:https ://github.com/sanusart/gists-backup 。它也知道分页、重复描述和缺失描述。

于 2014-03-13T21:45:42.243 回答
2

我编写了一个快速的 node.js 脚本作为练习,下载了所有 gist 并将它们以与原始 gist 相同的文件名保存在与“gist description”名称匹配的文件夹中。 https://gist.github.com/thomastraum/5227541

var request = require('request')
    , path = require('path')
    , fs = require('fs')
    , url = "https://api.github.com/users/thomastraum/gists"
    , savepath = './gists';

request(url, function (error, response, body) {

    if (!error && response.statusCode == 200) {

        gists = JSON.parse( body );
        gists.forEach( function(gist) {

            console.log( "description: ", gist.description );
            var dir = savepath + '/' + gist.description;

            fs.mkdir( dir, function(err){
                for(var file in gist.files){

                    var raw_url = gist.files[file].raw_url;
                    var filename = gist.files[file].filename;

                    console.log( "downloading... " + filename );
                    request(raw_url).pipe(fs.createWriteStream( dir + '/' + filename ));
                }
            });
        });

    }

});
于 2013-03-23T22:48:36.947 回答
1

这个红宝石宝石似乎可以帮助您解决问题。我还没有尝试过,但看起来很有希望。

第一的

gem install gisty

你需要把

export GISTY_DIR="$HOME/dev/gists"

在你的 .bashrc 或 .zshrc 这个目录是你的要点保存的地方。

你需要

git config --global github.user your_id
git config --global github.token your_token

在您的 .gitconfig 上添加上述配置

用法

  • gisty 发布文件 1 文件 2 ...

    将 file1 和 file2 发布到您的 gist

  • gisty private_post 文件 1 文件 2 ...

    私下发布 file1 和 file2

  • gisty同步

    同步到您的所有要点

  • gisty pull_all

    拉到本地仓库

  • 要点清单

    列出克隆的本地 gist 存储库

于 2011-08-16T00:26:43.903 回答
0

2021 年 3 月更新 (Python3)

如果用户有大量具有相同文件名的 gist,则效果很好。

import requests, json, time, uuid
headers = {"content-type" : "application/json"}
url =  'https://api.github.com/users/ChangeToYourTargetUser/gists?per_page=100&page='

for page in range(1,100):  #do pages start at 1 or 0?
    print('page: ' + str(page))
    r = requests.get(url+str(page), headers = headers)
    metadata_file = './data/my_gist_list.json'
    # Getting metadata
    prettyJson = json.dumps(r.json(), indent=4, sort_keys=True)
    f = open(metadata_file, 'w')
    f.write(prettyJson)

    print('Metadata obtained as {}'.format(metadata_file))

    # Downloading files
    data = r.json()
    counter = 0
    for i in data:
        time.sleep(1.1)
        files_node = i['files']
        file_name = [k for k in files_node][0]
        r = requests.get(files_node[file_name]['raw_url'])
        f = open('./data/{}'.format(str(uuid.uuid4())), 'w')
        f.write(r.text)
        f.close()
        print('Download' + str(i))
        counter += 1

    print('{} files successfully downloaded.'.format(counter))
于 2021-03-08T15:29:52.587 回答
0

如果您需要做的只是从特定用户那里下载所有要点,那么这个简单的 python 脚本会有所帮助。

特定用户的要点信息通过 API 公开

"https://api.github.com/users/" + username + "/gists"

您可以简单地循环通过 API 公开的 JSON,获取要点列表,执行克隆,或者简单地使用指定的原始 url 下载要点。下面的简单脚本循环遍历 JSON,提取文件名和原始 url 并下载所有要点并将其保存在本地文件夹中。

import requests

# Replace username with correct username
url = "https://api.github.com/users/" + username + "/gists"

resp = requests.get(url)
gists = resp.json()

for gist in gists:
    for file in gist["files"]:
        fname = gist["files"][file]["filename"]
        furl = gist["files"][file]["raw_url"]
        print("{}:{}".format(fname, furl)) # This lists out all gists

        Use this to download all gists
        pyresp = requests.get(furl)

        with open("../folder/" + fname, "wb") as pyfile:
            for chunk in pyresp.iter_content(chunk_size=1024):
                if chunk:
                    pyfile.write(chunk)
        print("{} downloaded successfully".format(fname))
于 2015-12-20T13:19:11.263 回答
0

我使用它,它就像一个魅力!


# first: mkdir user && cd user && cp /path/to/get_gists.py .
# python3 get_gists.py user
import requests
import sys
from subprocess import call

user = sys.argv[1]

r = requests.get('https://api.github.com/users/{0}/gists'.format(user))

for i in r.json():
    call(['git', 'clone', i['git_pull_url']])

    description_file = './{0}/description.txt'.format(i['id'])
    with open(description_file, 'w') as f:
        f.write('{0}\n'.format(i['description']))


于 2021-03-18T02:22:19.367 回答
0

那么GitHub CLI呢?

brew install gh

gh auth login

gh gist list [flags]

  Options:

    -L, --limit int   Maximum number of gists to fetch (default 10)
    --public          Show only public gists
    --secret          Show only secret gists

gh gist clone <gist> [<directory>] [-- <gitflags>...]
于 2021-07-21T11:52:40.390 回答