-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathautomate.py
More file actions
310 lines (211 loc) · 8.2 KB
/
automate.py
File metadata and controls
310 lines (211 loc) · 8.2 KB
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
import requests
import sys
import argparse
import os
import subprocess
import pathlib
import getpass
from github import Github
def repoCreate(username , passwrd , repo,private ,oauth,acess_token):
"""
desc : Create new github repository
params:
username (str): Github Username
passwrd (str): Github Password
repo (str): Repo Name
private (bool): Whether repo is private
"""
print()
url = 'https://api.github.com/user/repos' #Github's Endpoint
if(oauth):
if(private):
print(f"Creating new github private repository : {repo}")
print()
data= {"name":repo,"homepage": "https://github.com","private":True}
else:
print(f"Creating new github repository : {repo}")
print()
data= {"name":repo,"homepage": "https://github.com"}
## Make POST request
r = requests.post(url, json=data , auth =(username,passwrd))
print("Request Status : ",r.ok)
res = r.json()
if(not r.ok ):
print("Cannot create New Repository")
try :
print("Error Message : ",f"\"{r.json()['errors'][0]['message']}\"")
except :
print(r.json())
else :
print(f"Success: '{repo}' Github Repository created")
# print(r.json())
try :
http_url = str(res['clone_url'])
ssh_url = str(res['ssh_url'])
# print(http_url , ssh_url)
return http_url , ssh_url , True
except Exception as e:
print("Error occured while getting git_url")
print(e)
else :
try:
##Authenticate User
if(acess_token == "" or acess_token is None):
print("NO ACESS TOKEN FOUND")
return None,None,False
g = Github(acess_token)
user = g.get_user()
print("Sucess: User Authenticated\n")
try:
##Create Repo
if(private):
repoObj = user.create_repo(repo,private=True)
else:
repoObj = user.create_repo(repo,private=False)
print(f"Sucess: {repo} created")
try:
##GET Links
http_url = repoObj.clone_url
ssh_url = repoObj.ssh_url
return http_url,ssh_url,True
except:
print("Error: Cannot get http/ssh url")
except Exception as e:
print("Error : Cannot create repo")
print(e)
print()
except Exception as e :
print("Error: Authentication Failure")
print(e)
print()
return None,None,False
def makeProj(parent_dir , repo):
"""
desc : Create Local Folder in the given directory
params :
parent_dir (str): Parent Directory (default = ".")
repo (str): Name of the Local Directory to be created
"""
print()
dir_path = parent_dir + '/' + repo
try :
pathlib.Path(dir_path).mkdir(parents=True, exist_ok=False)
print("Success: Created Local Folder")
try :
os.chdir(dir_path)
return True
except Exception as e:
print(e)
except Exception as e :
print("Error occured during local Folder creation ")
print(e)
return False
def initGit(ssh_url,http_url,ssh,repo,readme):
"""
desc: Initialise git ,
Add README.md ,
Add remote origin ,
Push Initial Commit
params :
ssh_url (str): via SSH (only if ssh is True)
http_url (str): via HTTP (default)
ssh (bool): To add remote origin via SSH (default : False)
repo (str): Repo's name
"""
print()
p1 = subprocess.run(['git init'] , shell=True)
with open("README.md","w+") as f:
f.write(f"### {repo}")
if(readme):
print()
print("Custom README.md Initialization")
r = str(input("Enter: "))
with open("README.md","a+") as f:
f.write(f"\n {r}")
subprocess.run(['git' ,'add', 'README.md'])
subprocess.run(['git commit -m "init"'],shell=True)
if(ssh):
cmd = f"git remote add origin {ssh_url}"
print(cmd)
subprocess.run(cmd,shell=True)
else :
cmd = f"git remote add origin {http_url}"
print(cmd)
subprocess.run([cmd],shell=True)
subprocess.run('git push -u origin master',shell=True)
# git remote add origin git@github.com:arnabaghorai/New-Repo.git
def createBranch(branchName):
"""
desc : Initialize a branch at local git and pushes the same.
params:
branchName : BranchName
"""
if(branchName is not None and branchName!=""):
try:
cmd = f"git checkout -b {branchName}"
subprocess.run(cmd,shell=True)
with open("README.md","a+") as f:
f.write(f"\n#### Branch : {branchName}")
subprocess.run(['git' ,'add', 'README.md'])
subprocess.run(['git commit -m "branch init"'],shell=True)
cmd = f"git push -u origin {branchName}"
subprocess.run(cmd,shell=True)
except Exception as e:
print("Error: Cannot create Branch")
print(e)
print()
else:
print("Enter valid branch name")
parser = argparse.ArgumentParser(description='Automate Project Setup\n> Creates new repository in Github.\n> Makes a folder in the current directory\n> git init and add README.md in local setup\n> Add remote origin')
parser.add_argument('repo', type=str,help='Github repo Name')
parser.add_argument('-d','--dir', type=str, default=".",help='Path where local folder is created, default : (Current Folder) ')
parser.add_argument('-b','--branch', type=str, default=None,help='Name of Branch')
parser.add_argument('-s','--ssh', action='store_true',
default=False,
help='add new repo through cli via SSH')
parser.add_argument('--private', action='store_true',
default=False,
help='Initialise Private Repo')
parser.add_argument('--readme', action='store_true',
default=False,
help='Init custom README.md')
parser.add_argument('--oauth', action='store_true',
default=False,
help='Access via oauth instead of Acess Token ("WARNING OAuth is going to be deprecated')
def main():
args = parser.parse_args()
user = None
passwrd = None
oauth = args.oauth
branch = args.branch
repo = args.repo
readme = args.readme
parent_dir = args.dir
ssh = args.ssh
private = args.private
personal_acess_token = os.environ.get("GIT_ACESS_TOKEN",None)
if(not oauth):
if(personal_acess_token is None or personal_acess_token == ""):
print("!!!! NO PERSONAL ACESS TOKEN FOUND !!!!!")
print()
print(f"SET 'GIT_ACESS_TOKEN' as environment variable")
print(f"GIT_ACESS_TOKEN='PERSONAL_ACESS_TOKEN")
return
else :
print()
print("Basic username - password based auth may get deprecate anytime.It's not reliable")
print("GET PERSONAL ACESS TOKEN")
print()
if(user is None):
user = str(input("Enter Github Username: "))
if (passwrd is None):
passwrd = str(getpass.getpass("Enter Github Password: "))
http_url , ssh_url , flag = repoCreate(user,passwrd,repo,private,oauth,personal_acess_token)
if(flag):
if(makeProj(parent_dir,repo)):
initGit(ssh_url,http_url,ssh,repo,readme)
if(branch is not None):
createBranch(branch)
print()
if __name__ == "__main__":
main()