This repository has been archived by the owner on Jan 3, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfileops.py
136 lines (121 loc) · 4.69 KB
/
fileops.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
"""
This file does all the fancy git operations and file writing
"""
import os
import json
from pprint import pprint
from bs4 import BeautifulSoup
from sh import git
HR = 'https://www.hackerrank.com'
HR_REST = HR + '/rest'
CONTESTS = '/contests'
CHALLENGES = '/challenges'
SUBMISSIONS = '/submissions'
SUBMISSIONS_GROUPED = SUBMISSIONS + '/grouped'
def getFullPath(path):
return os.path.abspath(path)
def load(filename):
try:
return json.load(open(filename, 'r'))
except FileNotFoundError as e:
return None
def dump(filename, data):
json.dump(data, open(filename, 'w'))
def initializeDir(path, user, repo = None):
if not os.path.exists(path):
print('making directories')
os.makedirs(path)
os.chdir(path)
if os.path.exists('.git/'):
print('git respository already initialized')
return
print('initializing git repository')
git.init()
os.chmod(path + '/.git/', 0b111000000)
git.config('--local', 'user.name', '"' + user['name'] + '"')
git.config('--local', 'user.email', '"' + user['email'] + '"')
if repo:
git.remote.add('origin', repo)
def writeModels(models, html):
if not models:
return
print('writing models')
for t in sorted(models.keys()):
(m, ty) = models[t]
if ty == 'co':
try:
os.makedirs(m['model']['slug'])
except:
pass
os.chdir(m['model']['slug'])
if html:
writeContest(m)
elif ty == 'ch':
try:
os.chdir(m['contest_slug'])
except:
os.makedirs(m['contest_slug'])
os.chdir(m['contest_slug'])
if html:
writeChallenge(m)
elif ty == 'sub':
os.chdir(m['contest_slug'])
writeSubmission(m)
os.chdir('..')
def writeContest(contest):
model = contest['model']
hrurl = HR + CONTESTS + '/' + model['slug']
resturl = HR_REST + CONTESTS + '/' + model['slug']
challengehtml = '<ul>'
for (challengeSlug, challenge) in contest['challenges'].items():
challengehtml += '<li><a href="{}">{}</a></li>'.format(challengeSlug + '.html', challengeSlug)
challengehtml += '</ul>'
html = """<!DOCTYPE html>
<html><head></head><body>
<h1>{}</h1><a href="{}">Contest</a> <a href="{}">JSON</a><hr/>{}<hr/>
<h2>Challenges</h2>{}</body></html>
""".format(model['name'], hrurl, resturl, model['description_html'], challengehtml)
filename = 'index.html'
with open(filename, 'w') as f:
f.write(BeautifulSoup(html, 'html5lib').prettify() + '\n')
gitCommitModel(contest['model'], filename, 'contest created: ' + model['slug'])
def writeChallenge(challenge):
asseturl = 'https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_CHTML'
js = "MathJax.Hub.Config({tex2jax:{inlineMath:[['$','$'],['\\(','\\)']]}});"
hrurl = HR \
+ (CONTESTS + '/' + challenge['contest_slug'] if challenge['contest_slug'] != 'master' else '') \
+ CHALLENGES + '/' + challenge['slug']
jsonurl = HR_REST + CONTESTS + '/' + challenge['contest_slug'] + CHALLENGES + '/' + challenge['slug']
html = """<!DOCTYPE html>
<html><head><meta charset="UTF-8"/>
<script type="text/javascript" async src="{}">{}</script>
</head><body><h1>{}</h1><p><a href="{}">Challenge</a> <a href="{}">JSON</a></p><hr/>{}</body></html>
""".format(asseturl, js, challenge['name'], hrurl, jsonurl, challenge['body_html'])
filename = challenge['slug'] + '.html'
with open(filename, 'w') as f:
f.write(BeautifulSoup(html, "html5lib").prettify() + "\n")
gitCommitModel(challenge, filename, 'challenge created: ' + challenge['slug'])
def writeSubmission(sub):
filename = sub['challenge_slug'] + getFileExtension(sub)
with open(filename, 'w') as f:
f.write(sub['code'] + "\n")
msg = "{} ({}) {} {}".format(sub['name'], sub['language'], getFrac(sub['testcase_status']), sub['status'])
gitCommitModel(sub, filename, msg)
def gitCommitModel(m, filename, msg):
envDict = {'GIT_COMMITTER_DATE': m['created_at'], 'GIT_AUTHOR_DATE': m['created_at']}
git.add(filename)
git.commit(m=msg, _ok_code=[0,1], date=m['created_at'])
git.commit('--no-edit', amend=True, _env=envDict) # force date
def getFileExtension(submission):
lang = submission['language']
if lang == 'java' or lang == 'java8':
return '.java'
if lang == 'python' or lang == 'python3':
return '.py'
if lang == 'haskell':
return '.hs'
if lang == 'prolog' or lang == 'perl':
return '.pl'
return '.txt'
def getFrac(testcases):
return '[%d/%d]' % (sum(testcases), len(testcases))