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

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

使用方法

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

首先,安装PyGithub的库

1
pip install PyGithub

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
from github import Github
import time

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

# or using an access token, https://github.com/settings/tokens
# 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()
time.sleep(1)
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,具体我也没管。

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

注意,上面文件命名不能是github.py,必须是别的名字,否则会出现ImportError: cannot import name Github

开发中遇到的问题

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

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

1
2
3
/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

------ 本文结束------
坚持原创技术分享,您的支持将鼓励我继续创作!

欢迎关注我的其它发布渠道