This repository has been archived by the owner on Jun 16, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdelete.py
319 lines (285 loc) · 10.8 KB
/
delete.py
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
# encoding: utf-8
"""
@version: python3.6
@author: ‘eric‘
@license: Apache Licence
@contact: [email protected]
@site: 00123.ml:8000
@software: PyCharm
@file: delete.py
@time: 2018/6/16 21:44
"""
from http import cookiejar
import requests, click, logging
import sys
import prettytable as pt
from lxml import etree
from utils import *
base_url = 'https://github.com/'
headers = {
"Host": "github.com",
"Connection": "keep-alive",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "zh-CN,zh;q=0.9"
}
# Remove SSL warning
requests.packages.urllib3.disable_warnings()
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')
def get_cookie():
'''
获取登录界面authenticity_token、保存cookie
:return: None
'''
r = requests.get(url=base_url + 'login', headers=headers, verify=False)
cookie = r.cookies
respose_etree = etree.HTML(r.text);
# Get authenticity_token By xpath
authenticity_token = respose_etree.xpath('//input[@name="authenticity_token"]/@value')
set_config('authenticity_token', authenticity_token[0])
logging.info('已获取登录页authenticity_token')
serialize_cookie(cookie)
def login():
'''
登录,获取用户名、保存cookie
:return:
'''
cookie = deserialize_cookie()
data = {
"commit": "Sign in",
"utf8": "✓",
}
data.update({"authenticity_token": get_config('authenticity_token'),
"login": get_config('user_name'),
"password": get_config('password'),
})
r = requests.post(base_url + 'session', headers=headers, data=data, verify=False, cookies=cookie)
respose_etree = etree.HTML(r.text);
# 获取用户名
nick_name = respose_etree.xpath('//meta[@name="octolytics-actor-login"]/@content')
if len(nick_name) > 0:
set_config('nick_name', nick_name[0])
cookie = r.cookies
logging.info('登陆成功!')
set_config('isLogin', 'True')
else:
logging.info('登陆失败,请检查配置文件【conf.ini】用户名和密码!')
set_config('isLogin', 'False')
sys.exit(1)
serialize_cookie(cookie)
def get_authenticity_token():
'''
获取待删除项目的authenticity_token
:return:authenticity_token
'''
cookie = deserialize_cookie()
url = base_url + get_config('nick_name') + '/' + get_config('repo_name') + '/settings'
params = {
"_pjax": "%23js-repo-pjax-container"
}
r = requests.get(url, headers=headers, params=params, cookies=cookie, verify=False)
html = etree.HTML(r.text)
authenticity_token = html.xpath('//form[contains(@action,"delete")]//input[@name="authenticity_token"]/@value')
logging.info('获取被删authenticity_token成功!')
serialize_cookie(cookie)
return authenticity_token
def delete_repo():
'''
删除单个项目,从配置文件读取待删除项目名称repo_name
:return:
'''
logging.info('正在删除%s' % get_config('repo_name'))
data = {
"utf8": "✓",
"_method": "delete",
}
data.update({"authenticity_token": get_authenticity_token(),
"verify": get_config('repo_name'),
})
url = base_url + get_config('nick_name') + '/' + get_config('repo_name') + '/settings/delete'
r = requests.post(url, headers=headers, cookies=deserialize_cookie(), data=data, verify=False)
if r.status_code != 200:
logging.info('*' * 20 + '删除【%s】失败' % get_config('repo_name') + '*' * 20)
sys.exit(1)
logging.info('*' * 20 + '删除【%s】成功' % get_config('repo_name') + '*' * 20)
def get_repo_list(page):
'''
获取指定页面的项目名称&项目数量
:param page:
:return: re_repo_list==>该页项目名称集合,repo_nums==>该页项目数目
'''
url = 'https://github.com/' + get_config('nick_name')
params = {
"page": page,
"tab": "repositories"
}
raw_html = requests.get(url, params, cookies=deserialize_cookie(), headers=headers, verify=False)
if raw_html.status_code != 200 or get_config('isLogin') == 'False' or get_config('isLogin') == '':
get_cookie()
login()
url = 'https://github.com/' + get_config('nick_name')
raw_html = requests.get(url, params, cookies=deserialize_cookie(), headers=headers, verify=False)
e_html = etree.HTML(raw_html.text)
repo_list = e_html.xpath('//ul/li//a[@itemprop="name codeRepository"]/text()')
re_repo_list = [x.strip() for x in repo_list]
repo_nums = e_html.xpath('//a[@title="Repositories"]/span/text()')[0]
return re_repo_list, repo_nums
def get_fork_list(page):
'''
获取指定页面的Fork项目名称&项目数量
:param page:
:return: re_repo_list==>该页项目名称集合,repo_nums==>该页项目数目
'''
url = 'https://github.com/' + get_config('nick_name')
params = {
"language": "",
"page": page,
"q": "",
"tab": "repositories",
"type": "fork",
"utf8": "✓"
}
raw_html = requests.get(url, params, cookies=deserialize_cookie(), headers=headers, verify=False)
if raw_html.status_code != 200 or get_config('isLogin') == 'False' or get_config('isLogin') == '':
get_cookie()
login()
url = 'https://github.com/' + get_config('nick_name')
raw_html = requests.get(url, params, cookies=deserialize_cookie(), headers=headers, verify=False)
e_html = etree.HTML(raw_html.text)
repo_list = e_html.xpath('//ul/li//a[@itemprop="name codeRepository"]/text()')
re_repo_list = [x.strip() for x in repo_list]
repo_nums = e_html.xpath('//a[@title="Repositories"]/span/text()')[0]
return re_repo_list, repo_nums
def get_all_repo_list():
'''
获取当前账号所有项目名称集合
:return:all_repo_list==>>所有项目名称集合
'''
if get_config('isLogin') == 'False' or get_config('isLogin') == '':
get_cookie()
login()
d = get_repo_list(1)
all_repo_list = d[0]
repo_nums = int(d[1])
if repo_nums < 31:
return all_repo_list
else:
pages = repo_nums // 30 + 1
for i in range(2, pages + 1):
all_repo_list += get_repo_list(i)[0]
return all_repo_list
def get_all_fork_repo_list():
'''
获取当前账号所有项目名称集合
:return:所有fork项目名称集合
'''
if get_config('isLogin') == 'False' or get_config('isLogin') == '':
get_cookie()
login()
d = get_fork_list(1)
all_repo_list = d[0]
repo_nums = int(d[1])
if repo_nums < 31:
return all_repo_list
else:
pages = repo_nums // 30 + 1
for i in range(2, pages + 1):
all_repo_list += get_fork_list(i)[0]
return all_repo_list
def repo_table_list(flag, all_repo_list):
'''
使用prettytable在终端显示项目列表
:param flag: true==>不打印输出
:return:
'''
repo_list = all_repo_list
list_len = len(repo_list)
tb = pt.PrettyTable()
tb.field_names = ['ID_1', 'RepoName_1', 'ID_2', 'RepoName_2']
for i in range(0, list_len - 1, 2):
tb.add_row(['[' + str(i) + ']', repo_list[i], '[' + str(i + 1) + ']', repo_list[i + 1]])
if list_len % 2 == 1:
tb.add_row([list_len - 1, repo_list[-1], '*', '*'])
if flag == 'true':
print(tb)
return repo_list
def del_target(repo_name):
'''
按项目名称删除单个项目
:param repo_name: 项目名称
:return:
'''
set_config('repo_name', repo_name)
if get_config('isLogin') == 'False' or get_config('isLogin') == '':
get_cookie()
login()
get_authenticity_token()
delete_repo()
if __name__ == '__main__':
# click不易获取不定数量的参数,因此使用sys.argv获取命令参数
option = sys.argv[1]
if option == '-help' or option == '-h':
print('''
-ls:【打印所有项目列表】
-id:【以-ls项目ID删除项目,多个用空格隔开,请仔细确认被删除项目名称!】
-name:【以项目名称删除项目,多个用空格隔开】
-all:【删除所有项目,请谨慎使用!】
-fork:【删除所有fork的项目,请谨慎使用】
-h:【显示本帮助】
''')
sys.exit(1)
if get_config('user_name') == '' or get_config('password') == '':
logging.info('登陆失败,请检查配置文件【conf.ini】用户名和密码!')
sys.exit(1)
# 打印所有项目
elif option == '-ls':
repo_table_list('true', get_all_repo_list())
# 以项目名方式删除
elif option == '-name':
repo_list = sys.argv[2:]
confirm_status = input('确认删除%s?,按y确认' % str(repo_list))
if confirm_status == 'y':
set_config('pre_del', str(repo_list))
logging.info(repo_list)
for i in repo_list:
del_target(i)
repo_table_list('true', get_all_repo_list())
# 以ID删除
elif option == '-id':
pre_del_list = []
repo_id_list = sys.argv[2:]
repo_list = repo_table_list('false', get_all_repo_list())
for pre_del in repo_id_list:
try:
pre_del_list.append(repo_list[int(pre_del)])
except:
logging.info('删除失败,请重新获取项目列表')
sys.exit(1)
confirm_status = input('确认删除%s?,按y确认' % str(pre_del_list))
if confirm_status == 'y':
set_config('pre_del', str(pre_del_list))
logging.info(repo_id_list)
for i in pre_del_list:
del_target(i)
repo_table_list('true', get_all_repo_list())
# 删除所有项目
elif option == '-all':
repo_list = repo_table_list('false', get_all_repo_list())
confirm_status = input('确认删除所有项目????%s,按y确认' % str(repo_list))
if confirm_status == 'y':
set_config('pre_del', str(repo_list))
logging.info(repo_list)
for i in repo_list:
del_target(i)
# 删除所有fork项目
elif option == '-fork':
repo_list = repo_table_list('false', get_all_fork_repo_list())
confirm_status = input('确认删除所有Fork项目????%s,按y确认' % str(repo_list))
if confirm_status == 'y':
set_config('pre_del', str(repo_list))
logging.info(repo_list)
for i in repo_list:
del_target(i)