Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 94c9e1b

Browse files
Merge pull request avinashkranjan#388 from antrikshmisri/master
Fixes to Github Automation as mentioned in issue avinashkranjan#386
2 parents a815372 + 740c176 commit 94c9e1b

File tree

10 files changed

+256
-103
lines changed

10 files changed

+256
-103
lines changed

‎Github-Automation/colors.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
class logcolors:
2+
HEADER = '033円[95m'
3+
BLUE = '033円[94m'
4+
CYAN = '033円[96m'
5+
SUCCESS = '033円[92m'
6+
WARNING = '033円[93m'
7+
ERROR = '033円[91m'
8+
ENDC = '033円[0m'
9+
BOLD = '033円[1m'
10+
UNDERLINE = '033円[4m'

‎Github-Automation/diffcalc.py‎

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,23 @@
1+
from colors import logcolors
2+
from difflib import ndiff
3+
from utils import getMaxSpaces
14

2-
import difflib
35

4-
def getMaxSpaces(file):
5-
max = float('-inf')
6-
for ele in file:
7-
ele = ele.strip()
8-
if(len(ele) > max):
9-
max = len(ele)
10-
return max
116

12-
def calcDiff(firstFile , secondFile):
13-
diff = difflib.ndiff(firstFile , secondFile)
7+
def calcDiff(firstFile, secondFile):
8+
# calculate raw diff
9+
diff = ndiff(firstFile, secondFile)
10+
# calculate unique lines in secondfile
1411
deltainit = ''.join(x[2:] for x in diff if x.startswith('+ '))
12+
# reformat the lines
1513
deltainit = deltainit.split('\n')
1614
maxspacesinit = getMaxSpaces(deltainit)
17-
print('CHANGED LINES ARE:-\n' , '-' * maxspacesinit)
15+
print(f'{logcolors.BOLD}CHANGED LINES ARE{logcolors.ENDC}\n',
16+
f'{logcolors.BOLD}-{logcolors.ENDC}' * maxspacesinit)
17+
1818
for ele in deltainit:
19-
print(str(ele.strip()) , ' ' * (maxspacesinit - len(ele.strip())), '+|')
20-
print('' , '-' * maxspacesinit)
21-
19+
print(f'{logcolors.SUCCESS} {str(ele.strip())} {logcolors.ENDC}',
20+
' ' * (maxspacesinit - len(ele.strip())), '+')
21+
22+
print('', f'{logcolors.BOLD}-{logcolors.ENDC}' * maxspacesinit)
23+
return deltainit

‎Github-Automation/filechange.py‎

Lines changed: 37 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,38 @@
11
import os
2-
from os import listdir
3-
from os.path import isfile, join
42
import gitcommands as git
5-
import time
63
import diffcalc
4+
from ignore import getIgnoreFiles
5+
import logger
6+
from utils import getNestedFiles,read_file,commitAndUpdate
7+
from colors import logcolors
78
mypath = os.getcwd()
8-
nestfiles = []
9-
# add folders that you don't want to listen to
10-
ignoredirs = ['.git' , '.idea' , '__pycache__' , 'node_modules']
9+
10+
ignoredirs = getIgnoreFiles()
11+
print(ignoredirs)
12+
1113
# gets the list of all nested files
12-
def getNestedFiles(rootDir):
13-
for path , subdirs , files in os.walk(rootDir):
14-
if(all(ele not in path for ele in ignoredirs)):
15-
for name in files:
16-
nestfiles.append(join(path , name))
17-
return nestfiles
18-
19-
onlyfiles = getNestedFiles(mypath)
14+
onlyfiles = getNestedFiles(mypath,ignoredirs)
2015

21-
# Reads and appends the contents of each file
22-
def read_file():
23-
filecontent = []
24-
for file in onlyfiles:
25-
with open(onlyfiles[onlyfiles.index(file)], "r") as f:
26-
filecontent.append(f.readlines())
27-
return filecontent
2816

29-
def ischanged(url , branch):
17+
18+
def ischanged(url, branch,*args,**kwargs):
3019
changedfile = []
20+
diffarr = []
21+
# if uncommited data found perform git commands on them
22+
initbuffer = kwargs.get('initbuffer' , -1)
23+
if(initbuffer != -1):
24+
for obj in initbuffer:
25+
file = obj['path']
26+
diff = obj['changes']
27+
diffarr.append(diff)
28+
changedfile.append(file)
29+
30+
# Performing Git Commands for changed files
31+
commitAndUpdate(changedfile,diffarr,url,branch)
3132
print('Listening for changes....')
32-
initial = list(read_file())
33+
initial = list(read_file(onlyfiles))
3334
while True:
34-
current = list(read_file())
35+
current = list(read_file(onlyfiles))
3536
changeditem = []
3637
previtem = []
3738
if(current != initial):
@@ -45,21 +46,19 @@ def ischanged(url , branch):
4546
if ele not in initial:
4647
changeditem.append(ele)
4748
# calculating changed file's name
48-
for i in range(0 ,len(changeditem)):
49-
print('loop :-', i)
49+
for i in range(0, len(changeditem)):
50+
print('loop :-', i)
5051
changedfile.append(onlyfiles[current.index(changeditem[i])])
51-
print('Changed file is:-' , changedfile,'\n')
52+
print(f"Changed file is {logcolors.BOLD}{changedfile}{logcolors.ENDC}\n")
53+
5254
# Calculating Diff for previous and changed version of file
53-
diffcalc.calcDiff(previtem , changeditem[0])
55+
diff = diffcalc.calcDiff(previtem, changeditem[0])
56+
diffarr.append(diff)
57+
for file in changedfile:
58+
logger.writedata(path=file, diff=diff)
5459

55-
# Performing Git Commands For Changed File
56-
# Performing Git Add
57-
git.add(changedfile)
58-
# Performing Git Commit
59-
if(git.commit(changedfile) == False):
60-
print('Reverting Push')
61-
# Performing Git Push
62-
elif(len(changedfile) == 0):
63-
git.push(url , branch)
64-
initial = current
60+
# Performing Git Commands for changed files
61+
commitAndUpdate(changedfile,diffarr,url,branch)
6562

63+
initial = current
64+
# time.sleep(5)

‎Github-Automation/gitcommands.py‎

Lines changed: 30 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
11
from subprocess import call
22
from sys import platform as _platform
3+
from colors import logcolors
4+
5+
36
def init():
47
call('git init')
5-
# git add <filename>
8+
9+
610
def createReadme():
711
if _platform == "linux" or _platform == "linux2":
812
call('touch README.md')
@@ -12,38 +16,50 @@ def createReadme():
1216
call('type nul>README.md')
1317

1418

15-
# Windows
1619
def add(filelist):
1720
for file in filelist:
1821
# perform git add on file
19-
print("Adding" , file)
22+
print(f"{logcolors.SUCCESS}Adding{logcolors.ENDC}",
23+
file.split('\\')[-1])
2024
call(('git add ' + file))
2125

2226
# git commit -m "passed message"
23-
def commit(filelist):
27+
28+
29+
def commit(filelist,*args,**kwargs):
30+
diffarr = kwargs.get('diffarr' , -1)
2431
for file in filelist:
2532
# ask user for commit message
26-
msg = str(input('Enter the commit message for ' + file + ' or enter -r to reject commit'))
33+
msg = str(input(f'{logcolors.BOLD}Enter the commit message for{logcolors.ENDC} ' +
34+
file.split('\\')[-1] + f' {logcolors.BOLD}or enter {logcolors.ERROR}-r{logcolors.ENDC} to reject commit{logcolors.ENDC}'))
2735
# if msg == -r reject commit
2836
if(msg == '-r'):
37+
print(f'{logcolors.ERROR}commit rejected{logcolors.ENDC}')
38+
if(diffarr != -1):
39+
diffarr.remove(diffarr[filelist.index(file)])
2940
filelist.remove(file)
30-
print('commit rejected')
3141
call('cls', shell=True)
3242
return False
3343
# else execute git commit for the file
34-
#added a comment
44+
#added a comment
3545
else:
36-
filelist.remove(file)
3746
call('git commit -m "' + msg + '"')
38-
call('cls' , shell=True)
39-
47+
call('cls', shell=True)
48+
print(
49+
f'Commited {logcolors.CYAN}{file}{logcolors.ENDC} with msg: {logcolors.BOLD}{msg}{logcolors.ENDC}')
50+
51+
4052
def setremote(url):
4153
call('git remote add origin ' + url)
42-
54+
55+
4356
def setBranch(branch):
4457
call('git branch -M ' + branch)
45-
58+
4659
# git push
47-
def push(url , branch):
60+
61+
62+
def push(url, branch):
4863
call('git push -u ' + url + ' ' + branch)
49-
#added a comment
64+
call('cls', shell=True)
65+
print(f'{logcolors.SUCCESS}Successfully Pushed Changes{logcolors.ENDC}')

‎Github-Automation/ignore.py‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import os
2+
3+
cwd = os.getcwd()
4+
ignorepath = os.path.join(cwd, '.gitignore')
5+
6+
7+
def getIgnoreFiles():
8+
ignorefiles = []
9+
with open(ignorepath) as ignore:
10+
files = ignore.readlines()
11+
for file in files:
12+
file = ''.join(file.splitlines())
13+
if(file != ''):
14+
filepath = os.path.join(cwd , file)
15+
if(os.path.isfile(filepath) or os.path.isdir(filepath)):
16+
ignorefiles.append(file)
17+
return ignorefiles

‎Github-Automation/install.py‎

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,21 @@
11
from shutil import copy , copyfile
22
import os
33
dir = os.getcwd()
4-
files = []
5-
# files = ['diffcalc.py' , 'main.py' , 'filechange.py' , 'gitcommands.py' , 'repoInfo.py']
6-
for file in os.listdir(dir):
7-
if(file.endswith('.py') and file != 'install.py'):
8-
files.append(file)
9-
print(files)
104

5+
files = [file for file in os.listdir(dir) if file.endswith('.py') and file != 'install.py']
6+
files.append('tmp.json')
7+
print(files)
118
def checkForIgnore(dst):
129
return os.path.isfile(os.path.join(dst , '.gitignore'))
1310

1411
def addToIgnore(dst):
1512
with open(os.path.join(dst , '.gitignore') , "a") as f:
16-
f.write('\n/auto-scripts')
13+
f.write('\nauto-scripts\n.idea\n__pycache__\n.git')
1714
f.close()
1815

1916
def makeIgnore(dst):
2017
f = open(os.path.join(dst , '.gitignore') , "x")
21-
f.write('/auto-scripts')
18+
f.write('auto-scripts\n.idea\n__pycache__\n.git')
2219
f.close()
2320

2421
def copyfiles(file:str , dst:str):
@@ -33,7 +30,6 @@ def installfiles():
3330
else:
3431
print('.gitignore not found, creating one')
3532
makeIgnore(location)
36-
addToIgnore(location)
3733
os.makedirs(os.path.join(location , 'auto-scripts'))
3834
location = os.path.join(location , 'auto-scripts')
3935
print('Installing Files')

‎Github-Automation/logger.py‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import json
2+
import os
3+
from colors import logcolors
4+
import filechange
5+
jsonpath = os.path.join(os.getcwd(), 'auto-scripts' , 'tmp.json')
6+
buffer = []
7+
8+
9+
def writedata(*args, **kwargs):
10+
data = {}
11+
global buffer
12+
updatedbuffer = kwargs.get('buffer', -1)
13+
path = kwargs.get('path', None)
14+
diff = kwargs.get('diff', None)
15+
if(updatedbuffer != -1):
16+
buffer = updatedbuffer
17+
with open(jsonpath, 'w') as file:
18+
json.dump([obj for obj in buffer], file, indent=4)
19+
elif(path and diff):
20+
data['path'] = path
21+
data['changes'] = diff
22+
buffer.append(data)
23+
with open(jsonpath, 'w') as file:
24+
json.dump([obj for obj in buffer], file, indent=4)
25+
26+
27+
def updatedata(filename, diffarr):
28+
if(os.path.getsize(jsonpath) > 0):
29+
with open(jsonpath, 'r') as file:
30+
readdata = json.load(file)
31+
if(len(readdata) == 0):
32+
print('No changed file left')
33+
else:
34+
tmpdata,tmpfile,tmpdiff = readdata.copy(),filename.copy(),diffarr.copy()
35+
print('Found some changed files')
36+
for file,diff in zip(filename,diffarr):
37+
print(f'Removing {str(file)} from json file')
38+
for obj in readdata:
39+
if obj['path'] == file and obj['changes'] == diff:
40+
tmpdata.remove(obj)
41+
tmpfile.remove(file)
42+
tmpdiff.remove(diff)
43+
# make the original lists empty without changing address
44+
del filename[:],diffarr[:]
45+
writedata(buffer=tmpdata)
46+
47+
else:
48+
print('No data to read')
49+
50+
51+
def checkdata(url , branch):
52+
if(os.path.getsize(jsonpath) > 0):
53+
with open(jsonpath, 'r') as file:
54+
initdata = json.load(file)
55+
if(len(initdata) == 0):
56+
print(f'{logcolors.SUCCESS}Change tree clean{logcolors.ENDC}')
57+
else:
58+
filechange.ischanged(url , branch , initbuffer = initdata)
59+
else:
60+
print(f'{logcolors.ERROR}No changes found from previous session{logcolors.ENDC}')

‎Github-Automation/main.py‎

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,22 @@
1-
import repoInfo,filechange
2-
import gitcommands as git
1+
import repoInfo
2+
from filechange import ischanged
3+
from colors import logcolors
4+
import pyfiglet
5+
import logger
6+
from utils import initCommands
37
def init():
48
info = repoInfo.checkinfoInDir()
9+
url, branch = info
10+
logger.checkdata(url , branch)
511
if('n' in info):
6-
info.remove('n')
7-
git.init()
8-
git.createReadme()
9-
git.add(['.'])
10-
git.commit(['README.md'])
11-
git.setBranch(info[1])
12-
git.setremote(info[0])
13-
git.push(info[0] , info[1])
14-
print('initial setup done :)')
15-
filechange.ischanged(info[0] , info[1])
12+
initCommands(info)
1613
else:
17-
print('Retrieving info from git directory')
18-
filechange.ischanged(info[0] , info[1])
14+
print(f'{logcolors.BOLD}Retrieving info from git directory{logcolors.ENDC}')
15+
print(f'{logcolors.CYAN}URL:{logcolors.ENDC} {url} , {logcolors.CYAN}Branch:{logcolors.ENDC} {branch}')
16+
ischanged(url,branch)
17+
1918

2019
if __name__ == '__main__':
21-
init()
20+
f = pyfiglet.figlet_format('G - AUTO', font='5lineoblique')
21+
print(f"{logcolors.BOLD}{f}{logcolors.ENDC}")
22+
init()

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /