Skip to content

Commit 22c1dc2

Browse files
committed
contribute feature
1 parent b4d3b65 commit 22c1dc2

5 files changed

Lines changed: 255 additions & 1 deletion

File tree

contribute

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
#!/bin/bash
2+
3+
# Check if the first 3 arguments are provided
4+
if [ -z "$1" ] || [ -z "$2" ] || [ -z "$3" ]; then
5+
echo "Error: The first 3 arguments are mandatory."
6+
echo "Usage: ./contribute <Study-Name> <Full-Path-To-Study> <Author-Name> <Branch-Name> <PR-title> <PR-Body>"
7+
exit 1
8+
fi
9+
10+
# Set the last 3 arguments to "#" if not provided
11+
arg4=$4
12+
arg5=$5
13+
arg6=$6
14+
if [ -z "$4" ]; then
15+
arg4="#"
16+
fi
17+
if [ -z "$5" ]; then
18+
arg5="#"
19+
fi
20+
if [ -z "$6" ]; then
21+
arg6="#"
22+
fi
23+
python contribute.py $1 $2 $3 $arg4 $arg5 $arg6

contribute.bat

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
@echo off
2+
3+
REM Check if the first 3 arguments are provided
4+
if "%~1" == "" goto :missing_arg
5+
if "%~2" == "" goto :missing_arg
6+
if "%~3" == "" goto :missing_arg
7+
8+
REM Check and set default values for the last three arguments if not provided
9+
if "%~4"=="" (set arg4="#") else (set arg4=%~4)
10+
if "%~5"=="" (set arg5="#") else (set arg5=%~5)
11+
if "%~6"=="" (set arg6="#") else (set arg6=%~6)
12+
python contribute.py %1 %2 %3 %arg4% %arg5% %arg6%
13+
goto :eof
14+
15+
:missing_arg
16+
echo "Error: The first 3 arguments are mandatory."
17+
echo "Usage: ./contribute.bat <Study-Name> <Full-Path-To-Study> <Author-Name> <Branch-Name> <PR-title> <PR-Body>"
18+
19+
20+

contribute.py

Lines changed: 181 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,181 @@
1+
import github
2+
from github import Github
3+
import os,sys,time,platform,base64
4+
5+
# Intializing the Variables
6+
# Hashed token
7+
BOT_TOKEN = 'Z2l0aHViX3BhdF8xMUFYM1pBT1kwR0lTTm5jWFlObXdhX3hQa2xyOVdSZ0ZMRURGcERFNFBzbW9zZFFUTzZaNTBBZkcwY2dYSVNKZ2FCSUtNWUo3SGpXTnlxTFda'
8+
REPO_NAME = 'concore' #repo-name
9+
OWNER_NAME = 'parteekcoder' #bot
10+
STUDY_NAME = sys.argv[1]
11+
STUDY_NAME_PATH = sys.argv[2]
12+
AUTHOR_NAME = sys.argv[3]
13+
BRANCH_NAME = sys.argv[4]
14+
PR_TITLE = sys.argv[5]
15+
PR_BODY = sys.argv[6]
16+
17+
# if author name has spaces
18+
DIR_PATH = AUTHOR_NAME + '_' + STUDY_NAME
19+
UPSTREAM_OWNER = 'parteekcoder123'
20+
21+
22+
# Defining Functions
23+
def checkInputValidity():
24+
if AUTHOR_NAME=="" or STUDY_NAME=="" or STUDY_NAME=="":
25+
print("Please Provide necessary Inputs")
26+
exit(0)
27+
if not os.path.isdir(STUDY_NAME_PATH):
28+
print("Directory doesnot Exists.Invalid Path")
29+
exit(0)
30+
31+
32+
def getPRs(upstream_repo):
33+
try:
34+
return upstream_repo.get_pulls(head=f'{OWNER_NAME}:{BRANCH_NAME}')
35+
except Exception as e:
36+
print("Not able to fetch Status of your example.Please try after some time.")
37+
exit(0)
38+
39+
def printPR(pr):
40+
print(f'Check your example here https://github.com/{UPSTREAM_OWNER}/pulls/'+str(pr.number),end="")
41+
42+
def anyOpenPR(upstream_repo):
43+
pr = getPRs(upstream_repo)
44+
openPr=None
45+
for i in pr:
46+
if i.state=="open":
47+
openPr=i
48+
break
49+
return openPr
50+
51+
def commitAndUpdateRef(upstream_repo,repo,tree_content,commit,branch):
52+
try:
53+
new_tree = repo.create_git_tree(tree=tree_content,base_tree=commit.commit.tree)
54+
new_commit = repo.create_git_commit("commit message",new_tree,[commit.commit])
55+
if len(repo.compare(base=commit.commit.sha,head=new_commit.sha).files) == 0:
56+
print("Your don't have any new changes.May be your example is already accepted.If this is not the case try with different fields.")
57+
exit(0)
58+
ref = repo.get_git_ref("heads/"+branch.name)
59+
ref.edit(new_commit.sha,True)
60+
except Exception as e:
61+
print("failed to Upload your example.Please try after some time.",end="")
62+
exit(0)
63+
64+
65+
def appendBlobInTree(repo,content,file_path,tree_content):
66+
blob = repo.create_git_blob(content,'utf-8')
67+
tree_content.append( github.InputGitTreeElement(path=file_path,mode="100644",type="blob",sha=blob.sha))
68+
69+
70+
def fetchUpstream(repo,base_sha,branch):
71+
try:
72+
result = repo.compare(base=base_sha,head=branch.commit.commit.sha)
73+
if result.behind_by>0:
74+
ref = repo.get_git_ref("heads/"+branch.name)
75+
ref.edit(base_sha)
76+
except Exception as e:
77+
exit(0)
78+
79+
80+
def runWorkflow(repo,upstream_repo):
81+
openPR = anyOpenPR(upstream_repo)
82+
if openPR==None:
83+
workflow_runned = repo.get_workflow(id_or_name="pull_request.yml").create_dispatch(ref=BRANCH_NAME,inputs={'title':PR_TITLE,'body':PR_BODY})
84+
if not workflow_runned:
85+
print("Some Error Occured.Please try after some time")
86+
exit(0)
87+
else:
88+
printPRStatus(upstream_repo)
89+
else:
90+
print("Successfully uploaded all files,your example is in waiting.Please wait for us to accept it.",end="")
91+
printPR(openPR)
92+
93+
def printPRStatus(upstream_repo):
94+
try:
95+
time.sleep(15)
96+
openPR = anyOpenPR(upstream_repo)
97+
if openPR==None:
98+
print("Someting went wrong or your example already exist.If this is not the case try with different fields")
99+
exit(0)
100+
printPR(openPR)
101+
except Exception as e:
102+
print("Your example successfully uploaded but unable to fetch status.Please try again")
103+
104+
105+
def isImageFile(filename):
106+
image_extensions = ['.jpeg', '.jpg', '.png']
107+
_, file_extension = os.path.splitext(filename)
108+
return file_extension.lower() in image_extensions
109+
110+
# Encode Github Token
111+
def encode_token(token):
112+
encoded_bytes = base64.b64encode(token.encode('utf-8'))
113+
encoded_token = encoded_bytes.decode('utf-8')
114+
return encoded_token
115+
116+
117+
# Decode Github Token
118+
def decode_token(encoded_token):
119+
decoded_bytes = base64.b64decode(encoded_token.encode('utf-8'))
120+
decoded_token = decoded_bytes.decode('utf-8')
121+
return decoded_token
122+
123+
124+
# check if directory path is Valid
125+
checkInputValidity()
126+
127+
128+
# Authenticating Github with Access token
129+
try:
130+
if BRANCH_NAME=="#":
131+
BRANCH_NAME=AUTHOR_NAME+"_"+STUDY_NAME
132+
if PR_TITLE=="#":
133+
PR_TITLE="Contributing Study "+AUTHOR_NAME+" "+STUDY_NAME
134+
if PR_BODY=="#":
135+
PR_BODY="Study Contributed by "+ AUTHOR_NAME
136+
g = Github(decode_token(BOT_TOKEN))
137+
repo = g.get_user(OWNER_NAME).get_repo(REPO_NAME)
138+
upstream_repo = g.get_repo(f'{UPSTREAM_OWNER}/{REPO_NAME}') #controlcore-Project/concore
139+
base_ref = upstream_repo.get_branch(repo.default_branch)
140+
branches = repo.get_branches()
141+
BRANCH_NAME = BRANCH_NAME.replace(" ","_")
142+
DIR_PATH = DIR_PATH.replace(" ","_")
143+
is_present = any(branch.name == BRANCH_NAME for branch in branches)
144+
except:
145+
print("Some error occured.Authentication failed",end="")
146+
exit(0)
147+
148+
149+
try:
150+
# If creating PR First Time
151+
# Create New Branch for that exmaple
152+
if not is_present:
153+
repo.create_git_ref(f'refs/heads/{BRANCH_NAME}', base_ref.commit.sha)
154+
# Get current branch
155+
branch = repo.get_branch(branch=BRANCH_NAME)
156+
except Exception as e:
157+
print("Not able to create study for you.Please try again after some time",end="")
158+
exit(0)
159+
160+
161+
tree_content = []
162+
163+
try:
164+
for root, dirs, files in os.walk(STUDY_NAME_PATH):
165+
for filename in files:
166+
path = os.path.join(root, filename)
167+
if isImageFile(filename):
168+
with open(path, 'rb') as file:
169+
image = file.read()
170+
content = base64.b64encode(image).decode('utf-8')
171+
else:
172+
with open(path, 'r') as file:
173+
content = file.read()
174+
file_path = f'{DIR_PATH+path.removeprefix(STUDY_NAME_PATH)}'
175+
if(platform.uname()[0]=='Windows'): file_path=file_path.replace("\\","/")
176+
appendBlobInTree(repo,content,file_path,tree_content)
177+
commitAndUpdateRef(upstream_repo,repo,tree_content,base_ref.commit,branch)
178+
runWorkflow(repo,upstream_repo)
179+
except Exception as e:
180+
print("Some error Occured.Please try again after some time.",end="")
181+
exit(0)

fri/server/main.py

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
from werkzeug.utils import secure_filename
33
import os
44
import subprocess
5-
from subprocess import call
5+
from subprocess import call,check_output
66
from pathlib import Path
77
import json
88
import platform
@@ -169,6 +169,35 @@ def clear(dir):
169169
resp.status_code = 500
170170
return resp
171171

172+
@app.route('/contribute', methods=['POST'])
173+
def contribute():
174+
try:
175+
data = request.json
176+
PR_TITLE = data.get('title')
177+
PR_BODY = data.get('desc')
178+
AUTHOR_NAME = data.get('auth')
179+
STUDY_NAME = data.get('study')
180+
STUDY_NAME_PATH = data.get('path')
181+
BRANCH_NAME = data.get('branch')
182+
if(platform.uname()[0]=='Windows'):
183+
proc=check_output(["contribute",STUDY_NAME,STUDY_NAME_PATH,AUTHOR_NAME,BRANCH_NAME,PR_TITLE,PR_BODY],cwd=concore_path,shell=True)
184+
else:
185+
proc = check_output(["./contribute",STUDY_NAME,STUDY_NAME_PATH,AUTHOR_NAME,BRANCH_NAME,PR_TITLE,PR_BODY],cwd=concore_path)
186+
output_string = proc.decode()
187+
status=200
188+
if output_string.find("/pulls/")!=-1:
189+
status=200
190+
elif output_string.find("error")!=-1:
191+
status=501
192+
else:
193+
status=400
194+
return jsonify({'message': output_string}),status
195+
except Exception as e:
196+
print(e)
197+
output_string = "Some Error occured.Please try after some time"
198+
status=501
199+
return jsonify({'message': output_string}),status
200+
172201
# to download /download/<dir>?fetch=<downloadfile>. For example, /download/test?fetchDir=xyz&fetch=u
173202
@app.route('/download/<dir>', methods=['POST', 'GET'])
174203
def download(dir):

requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,4 @@ numpy
55
scipy
66
matplotlib
77
cvxopt
8+
PyGithub

0 commit comments

Comments
 (0)