Skip to content

Commit

Permalink
FEAT: NEW GRAPH MODULE
Browse files Browse the repository at this point in the history
  • Loading branch information
anmol098 committed Jul 28, 2020
1 parent ef84598 commit 09764da
Show file tree
Hide file tree
Showing 4 changed files with 176 additions and 168 deletions.
9 changes: 9 additions & 0 deletions action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,15 @@ inputs:
description: "Show the Total Lines of code written Badge till date"
default: "False"

SHOW_LANGUAGE_PER_REPO:
required: false
description: ""
default: "True"

SHOW_LOC_CHART:
required: false
description: ""
default: "True"



Expand Down
108 changes: 52 additions & 56 deletions loc.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import datetime
from string import Template
import matplotlib.pyplot as plt
from io import StringIO,BytesIO
from io import StringIO, BytesIO
from dotenv import load_dotenv
import time

Expand All @@ -15,70 +15,70 @@

class LinesOfCode:

def __init__(self,id,username,ghtoken, repositoryData):
self.id=id
self.username=username
def __init__(self, id, username, ghtoken, repositoryData):
self.id = id
self.username = username

self.g = Github(ghtoken)
self.headers = {"Authorization": "Bearer " + ghtoken}
self.repositoryData=repositoryData
self.g = Github(ghtoken)
self.headers = {"Authorization": "Bearer " + ghtoken}
self.repositoryData = repositoryData

def calculateLoc(self):
result=self.repositoryData
yearly_data={}
result = self.repositoryData
yearly_data = {}
for repo in result['data']['user']['repositories']['edges']:
print(repo)
self.getCommitStat(repo['node'],yearly_data)
time.sleep(0.7)
print(repo)
self.getCommitStat(repo['node'], yearly_data)
time.sleep(0.7)
print("\n\n")
print(yearly_data)
graph=BarGraph(yearly_data)
graph_file=graph.build_graph()
print("here")
graph = BarGraph(yearly_data)
graph_file = graph.build_graph()
self.pushChart()

def run_query_v3(self,nameWithOwner):
endPoint='https://api.github.com/repos/'+nameWithOwner+'/stats/code_frequency'
def run_query_v3(self, nameWithOwner):
endPoint = 'https://api.github.com/repos/' + nameWithOwner + '/stats/code_frequency'
# print(endPoint)
request = requests.get(endPoint, headers=self.headers)
if request.status_code == 401:
raise Exception("Invalid token {}. {}".format(request.status_code, nameWithOwner))
raise Exception("Invalid token {}. {}".format(request.status_code, nameWithOwner))
return request.json()

def getQuarter(self,timeStamp):
month=datetime.datetime.fromtimestamp(timeStamp).month
if month>=1 and month<=4:
return 1
elif month>=5 and month<=8:
return 2
elif month>=9 and month<=12:
return 3

def getQuarter(self, timeStamp):
month = datetime.datetime.fromtimestamp(timeStamp).month
if month >= 1 and month <= 4:
return 1
elif month >= 5 and month <= 8:
return 2
elif month >= 9 and month <= 12:
return 3

def getCommitStat(self,repoDetails,yearly_data):
result= self.run_query_v3(repoDetails['nameWithOwner'])
this_year=datetime.datetime.utcnow().year
def getCommitStat(self, repoDetails, yearly_data):
result = self.run_query_v3(repoDetails['nameWithOwner'])
this_year = datetime.datetime.utcnow().year

for i in range(len(result)):
curr_year=datetime.datetime.fromtimestamp(result[i][0]).year
# if curr_year != this_year:
quarter=self.getQuarter(result[i][0])
if repoDetails['primaryLanguage'] is not None:

if curr_year not in yearly_data:
yearly_data[curr_year]={}
if quarter not in yearly_data[curr_year]:
yearly_data[curr_year][quarter]={}
if repoDetails['primaryLanguage']['name'] not in yearly_data[curr_year][quarter]:
yearly_data[curr_year][quarter][repoDetails['primaryLanguage']['name']]=0
yearly_data[curr_year][quarter][repoDetails['primaryLanguage']['name']]+=(result[i][1]+result[i][2])

#to find total

# if 'total' not in yearly_data[curr_year]:
# yearly_data[curr_year]['total']={}
# if repoDetails['primaryLanguage']['name'] not in yearly_data[curr_year]['total']:
# yearly_data[curr_year]['total'][repoDetails['primaryLanguage']['name']]=0
# yearly_data[curr_year]['total'][repoDetails['primaryLanguage']['name']]+=(result[i][1]+result[i][2])
curr_year = datetime.datetime.fromtimestamp(result[i][0]).year
# if curr_year != this_year:
quarter = self.getQuarter(result[i][0])
if repoDetails['primaryLanguage'] is not None:

if curr_year not in yearly_data:
yearly_data[curr_year] = {}
if quarter not in yearly_data[curr_year]:
yearly_data[curr_year][quarter] = {}
if repoDetails['primaryLanguage']['name'] not in yearly_data[curr_year][quarter]:
yearly_data[curr_year][quarter][repoDetails['primaryLanguage']['name']] = 0
yearly_data[curr_year][quarter][repoDetails['primaryLanguage']['name']] += (result[i][1] + result[i][2])

# to find total

# if 'total' not in yearly_data[curr_year]:
# yearly_data[curr_year]['total']={}
# if repoDetails['primaryLanguage']['name'] not in yearly_data[curr_year]['total']:
# yearly_data[curr_year]['total'][repoDetails['primaryLanguage']['name']]=0
# yearly_data[curr_year]['total'][repoDetails['primaryLanguage']['name']]+=(result[i][1]+result[i][2])

def pushChart(self):
repo = self.g.get_repo(f"{self.username}/{self.username}")
Expand All @@ -88,13 +88,9 @@ def pushChart(self):
contents = repo.get_contents("charts/bar_graph.png")
repo.update_file(contents.path, "Charts Added", data, contents.sha)
except Exception as e:
repo.create_file("charts/bar_graph.png", "Initial Commit",data)
repo.create_file("charts/bar_graph.png", "Initial Commit", data)
print("pushed")





# if __name__ == '__main__':
# try:
# g = Github(ghtoken)
Expand All @@ -103,7 +99,7 @@ def pushChart(self):
# username = user_data["data"]["viewer"]["login"]
# id = user_data["data"]["viewer"]["id"]
# print("user {} id {}".format(username, id))

# getLoc()

# # repo = g.get_repo(f"{username}/{username}")
Expand All @@ -117,4 +113,4 @@ def pushChart(self):
# # content=new_readme, sha=contents.sha, branch='master')
# # print("Readme updated")
# except Exception as e:
# print("Exception Occurred" + str(e))
# print("Exception Occurred" + str(e))
28 changes: 13 additions & 15 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
'''
Readme Development Metrics With waka time progress
'''

import locale
import re
import os
import base64
Expand All @@ -12,8 +12,6 @@
from github import Github, GithubException
import datetime
from string import Template
import matplotlib.pyplot as plt
from io import StringIO,BytesIO
from dotenv import load_dotenv
from loc import LinesOfCode

Expand All @@ -33,9 +31,10 @@
showCommit = os.getenv('INPUT_SHOW_COMMIT')
showLanguage = os.getenv('INPUT_SHOW_LANGUAGE')
show_loc = os.getenv('INPUT_SHOW_LINES_OF_CODE')
showLanguagePerRepo= os.getenv('INPUT_LANGUAGE_PER_REPO')
showLocChart='y' if (os.getenv('LOC_CHART') is None) else os.getenv('LOC_CHART')
show_waka_stats='n' if waka_key is None else 'y'

showLanguagePerRepo = os.getenv('INPUT_SHOW_LANGUAGE_PER_REPO')
showLocChart = os.getenv('INPUT_SHOW_LOC_CHART')
show_waka_stats = 'y'
# The GraphQL query to get commit data.
userInfoQuery = """
{
Expand Down Expand Up @@ -90,10 +89,11 @@ def run_v3_api(query):
raise Exception(
"Query failed to run by returning code of {}. {},... {}".format(request.status_code, query, request.json()))


repositoryListQuery = Template("""
{
user(login: "$username") {
repositories(orderBy: {field: CREATED_AT, direction: ASC}, last: 100, affiliations: [OWNER, COLLABORATOR, ORGANIZATION_MEMBER], isFork: false) {
repositories(orderBy: {field: CREATED_AT, direction: ASC}, last: 5, affiliations: [OWNER, COLLABORATOR, ORGANIZATION_MEMBER], isFork: false) {
totalCount
edges {
node {
Expand Down Expand Up @@ -132,6 +132,7 @@ def run_v3_api(query):
}
""")


def run_query(query):
request = requests.post('https://api.github.com/graphql', json={'query': query}, headers=headers)
if request.status_code == 200:
Expand Down Expand Up @@ -278,11 +279,11 @@ def generate_commit_list(tz):
string = string + '**' + title + '** \n\n' + '```text\n' + make_commit_list(one_day) + '\n\n```\n'
string = string + '📅 **' + days_title + '** \n\n' + '```text\n' + make_commit_list(dayOfWeek) + '\n\n```\n'


def get_waka_time_stats():
stats=''
try:
request = requests.get(
f"https://wakatime.com/api/v1/users/current/stats/last_7_days?api_key={waka_key}")
stats = ''
request = requests.get(
f"https://wakatime.com/api/v1/users/current/stats/last_7_days?api_key={waka_key}")

if request.status_code != 401:
data = request.json()
Expand Down Expand Up @@ -366,9 +367,6 @@ def get_stats():
'''Gets API data and returns markdown progress'''

stats = ''
if showCommit.lower() in ['true', '1', 't', 'y', 'yes']:
stats = stats + generate_commit_list() + '\n\n'

repositoryList = run_query(repositoryListQuery.substitute(username=username, id=id))

if showLanguagePerRepo.lower() in ['true', '1', 't', 'y', 'yes']:
Expand All @@ -386,6 +384,7 @@ def get_stats():

return stats


def decode_readme(data: str):
'''Decode the contets of old readme'''
decoded_bytes = base64.b64decode(data)
Expand Down Expand Up @@ -420,4 +419,3 @@ def generate_new_readme(stats: str, readme: str):
print("Readme updated")
except Exception as e:
print("Exception Occurred" + str(e))

Loading

0 comments on commit 09764da

Please sign in to comment.