Python脚本实现Github上fork项目与原项目同步更新

可能会有一些人在github上浏览项目的时候,感觉项目不错,就会fork一下,但是随着fork的项目越来越多,如何保持fork的项目与原项目同步更新是一个大问题,之前我都是手动比较,手动delete,然后重新fork,感觉很麻烦。后来,从这里得到了一些灵感,写了一个Python脚本来实现这个过程。

使用方法

下面的代码在windows10,Python3.6下面实验的。

首先,安装PyGithub的库

pip install PyGithub

接着代码如下,使用该代码需要更改的地方为,第4行的账户名和密码。如果你有一些代码仓库不想更新,可以在代码的第12行,添加'用户名 + / + 仓库名',例如,下面我的这里就是'lizhaoda/hexo-theme-next'

from github import Github

# using username and password
g = Github("zdaiot", "xxxxxxxx")

# or using an access token
# g = Github("access_token")

g_user = g.get_user()

# put the ignore repo in this list. They will not update
ignore_repos = ['zdaiot/hexo-theme-next']

amount = 0
count = 0

# Then play with your Github objects:
for repo in g_user.get_repos():
    amount += 1
    # print(repo.name,repo.fork, repo.parent, repo.source)
    if repo.fork:
        repo_full_name = repo.full_name
        repo_commit = repo.get_branch("master").commit.sha
        
        repo_parent = repo.parent
        repo_parent_full_name = repo_parent.full_name
        repo_parent_commit = repo_parent.get_branch("master").commit.sha
        
        if (not repo_commit == repo_parent_commit) and (repo_full_name not in ignore_repos):
            print(repo_full_name, repo_commit)
            print(repo_parent_full_name, repo_parent_commit)
            print('{} now is different form the parent!'.format(repo_full_name))
            
            repo.delete()
            g_user.create_fork(repo_parent)
            
            print('{} now is update!\n'.format(repo_full_name))
            count += 1
        else:
            print('{} now is up to date!\n'.format(repo_full_name))

print('total repos:', amount)
print('update repos:', count)

注意,可能在运行过程中,出现下面bug,重新运行一遍就行,这个是库里面的bug,具体我也没管。

ConnectionError: HTTPSConnectionPool(host='api.github.com', port=443): Max retries exceeded with url: /user/repos (Caused by NewConnectionError(': Failed to establish a new connection: [Errno 11003] getaddrinfo failed',))

开发中遇到的问题

在仓库的官方文档为这里,官方实例如下。

官方API与github API对应关系在这里。在该页面搜索,发现仓库delete对应的文档如下:

/repos/:owner/:repo/keys/:id
GET: github.Repository.Repository.get_key()
DELETE: github.RepositoryKey.RepositoryKey.delete()

点击github.RepositoryKey.RepositoryKey.delete()链接,发现对于github.RepositoryKey.RepositoryKey对象有delete()的方法,而该仓库readme中的例子,打印出变量repo的类型,正好是github.RepositoryKey.RepositoryKey,所以也就可以删除。

参考文献

PyGithub
PyGithub官网文档
PyGithub官网实例
PyGithub API与github API对应关系在
PyGithub demo


One more thing

更多关于人工智能、Python、C++、计算机等知识,欢迎访问我的个人博客进行交流, 点这里~~

你可能感兴趣的:(Python)