-
Notifications
You must be signed in to change notification settings - Fork 5
/
contests.py
311 lines (253 loc) · 10.3 KB
/
contests.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
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
309
310
311
import os
import logging
from typing import (
NamedTuple,
Mapping,
Any,
Sequence,
List,
Optional,
Dict,
Set,
)
import omegaup.api
import repository
import json
import datetime
import yaml
_CONFIG_FILE = 'contest.yaml'
class Contest(NamedTuple):
"""Represents a single contest."""
path: str
title: str
config: Mapping[str, Any]
@staticmethod
def load(contestPath: str, rootDirectory: str) -> 'Contest':
"""Load a single contest from the path."""
with open(os.path.join(rootDirectory, contestPath, _CONFIG_FILE)) as f:
problemConfig = yaml.safe_load(f)
return Contest(path=contestPath,
title=problemConfig['title'],
config=problemConfig)
def contests(allContests: bool = False,
contestPaths: Sequence[str] = (),
rootDirectory: Optional[str] = None) -> List[Contest]:
"""Gets the list of contests that will be considered.
If `allContests` is passed, all the contests that are declared in
`contests.json` will be returned. Otherwise, only those that have
differences with `upstream/main`.
"""
if rootDirectory is None:
rootDirectory = repository.repositoryRoot()
logging.info('Loading contests...')
if contestPaths:
# Generate the Contest objects from just the path. The title is ignored
# anyways, since it's read from the configuration file in the contest
# directory for anything important.
return [
Contest.load(contestPath=contestPath, rootDirectory=rootDirectory)
for contestPath in contestPaths
]
with open(os.path.join(rootDirectory, 'problems.json'), 'r') as p:
config = json.load(p)
configContests: List[Contest] = []
for contest in config['contests']:
if contest.get('disabled', False):
logging.warning('Contest %s disabled. Skipping.', contest['title'])
continue
configContests.append(
Contest.load(contestPath=contest['path'],
rootDirectory=rootDirectory))
if allContests:
logging.info('Loading everything as requested.')
return configContests
changes = repository.gitDiff(rootDirectory)
contests: List[Contest] = []
for contest in configContests:
logging.info('Loading %s.', contest.title)
if contest.path not in changes:
logging.info('No changes to %s. Skipping.', contest.title)
continue
contests.append(contest)
return contests
def date_to_timestamp(date: str) -> int:
return int(
datetime.datetime.strptime(date, '%Y-%m-%dT%H:%M:%SZ').timestamp())
def upsertContest(
client: omegaup.api.Client,
contestPath: str,
canCreate: bool,
timeout: datetime.timedelta,
) -> None:
"""Upsert a contest to omegaUp given the configuration."""
with open(os.path.join(contestPath, _CONFIG_FILE)) as f:
contestConfig = yaml.safe_load(f)
logging.info('Upserting contest %s...', contestConfig['title'])
title = contestConfig['title']
alias = contestConfig['alias']
misc = contestConfig['misc']
languages = misc['languages']
if languages == 'all':
misc['languages'] = ','.join((
'c11-clang',
'c11-gcc',
'cpp11-clang',
'cpp11-gcc',
'cpp17-clang',
'cpp17-gcc',
'cpp20-clang',
'cpp20-gcc',
'cs',
'go',
'hs',
'java',
'js',
'kt',
'lua',
'pas',
'py2',
'py3',
'rb',
'rs',
))
elif languages == 'karel':
misc['languages'] = 'kj,kp'
elif languages == 'none':
misc['languages'] = ''
payload = {
'title': title,
'admission_mode': misc['admission_mode'],
'description': contestConfig.get('description', ''),
'feedback': misc["feedback"],
'finish_time': date_to_timestamp(contestConfig['finish_time']),
'languages': misc['languages'],
'penalty': misc['penalty']['time'],
'penalty_calc_policy': misc['penalty']['calc_policy'],
'penalty_type': misc['penalty']['type'],
'points_decay_factor': misc['penalty']['points_decay_factor'],
'requests_user_information': str(misc['requests_user_information']),
'score_mode': misc['score_mode'],
'scoreboard': misc['scoreboard'],
'show_scoreboard_after': misc['show_scoreboard_after'],
'submissions_gap': misc['submissions_gap'],
'start_time': date_to_timestamp(contestConfig['start_time']),
'window_length': contestConfig.get('window_length', None),
}
exists = client.contest.details(contest_alias=alias,
check_=False)["status"] == 'ok'
if not exists:
if not canCreate:
raise Exception("Contest doesn't exist!")
logging.info("Contest doesn't exist. Creating contest.")
endpoint = '/api/contest/create/'
payload['alias'] = alias
else:
endpoint = '/api/contest/update/'
payload['contest_alias'] = alias
client.query(endpoint, payload, timeout_=timeout)
# Adding admins
targetAdmins: Sequence[str] = contestConfig.get('admins',
{}).get('users', [])
targetAdminGroups: Sequence[str] = contestConfig.get('admins',
{}).get('groups', [])
allAdmins = client.contest.admins(contest_alias=alias)
if len(targetAdmins) > 0:
admins = {
a['username'].lower()
for a in allAdmins['admins'] if a['role'] == 'admin'
}
desiredAdmins = {admin.lower() for admin in targetAdmins}
clientAdmin: Set[str] = set()
if client.username:
clientAdmin.add(client.username.lower())
adminsToRemove = admins - desiredAdmins - clientAdmin
adminsToAdd = desiredAdmins - admins - clientAdmin
for admin in adminsToAdd:
logging.info('Adding contest admin: %s', admin)
client.contest.addAdmin(contest_alias=alias, usernameOrEmail=admin)
for admin in adminsToRemove:
logging.info('Removing contest admin: %s', admin)
client.contest.removeAdmin(contest_alias=alias,
usernameOrEmail=admin)
adminGroups = {
a['alias'].lower()
for a in allAdmins['group_admins'] if a['role'] == 'admin'
}
desiredGroups = {group.lower() for group in targetAdminGroups}
groupsToRemove = adminGroups - desiredGroups
groupsToAdd = desiredGroups - adminGroups
for group in groupsToAdd:
logging.info('Adding contest admin group: %s', group)
client.contest.addGroupAdmin(contest_alias=alias, group=group)
for group in groupsToRemove:
logging.info('Removing contest admin group: %s', group)
client.contest.removeGroupAdmin(contest_alias=alias, group=group)
# Adding problems
targetProblems: Sequence[Dict[str,
Any]] = contestConfig.get('problems', [])
allProblems = client.contest.problems(contest_alias=alias)
problems = {
p['alias'].lower(): {
'points': p['points'],
'order_in_contest': p['order'],
}
for p in allProblems['problems']
}
desiredProblems = {
problem['alias'].lower(): {
'points': problem.get('points', 100),
'order_in_contest': problem.get('order_in_contest', idx + 1),
}
for idx, problem in enumerate(targetProblems)
}
problemsToRemove = problems.keys() - desiredProblems
problemsToUpsert = (desiredProblems.keys() - problems.keys()) | {
problem
for problem in problems
if problem in problems and problem in desiredProblems and
(desiredProblems[problem] != problems[problem])
}
for problem in problemsToUpsert:
logging.info('Upserting contest problem: %s', problem)
client.contest.addProblem(
contest_alias=alias,
problem_alias=problem,
order_in_contest=desiredProblems[problem]['order_in_contest'],
points=desiredProblems[problem]['points'])
for problem in problemsToRemove:
logging.info('Removing contest problem: %s', problem)
client.contest.removeProblem(contest_alias=alias,
problem_alias=problem)
# Adding contestants
targetContestants: Sequence[str] = contestConfig.get('contestants',
{}).get('users', [])
targetContestantGroups: Sequence[str] = contestConfig.get(
'contestants', {}).get('groups', [])
allContestants = client.contest.users(contest_alias=alias)
if len(targetContestants) > 0:
contestants = {c['username'].lower() for c in allContestants['users']}
desiredContestants = {
contestant.lower()
for contestant in targetContestants
}
contestantsToRemove = contestants - desiredContestants
contestantsToAdd = desiredContestants - contestants
for contestant in contestantsToAdd:
logging.info('Adding contestant: %s', contestant)
client.contest.addUser(contest_alias=alias,
usernameOrEmail=contestant)
for contestant in contestantsToRemove:
logging.info('Removing contestant: %s', contestant)
client.contest.removeUser(contest_alias=alias,
usernameOrEmail=contestant)
contestantGroups = {c['alias'].lower() for c in allContestants['groups']}
desiredGroups = {group.lower() for group in targetContestantGroups}
groupsToRemove = contestantGroups - desiredGroups
groupsToAdd = desiredGroups - contestantGroups
for group in groupsToAdd:
logging.info('Adding contestant group: %s', group)
client.contest.addGroup(contest_alias=alias, group=group)
for group in groupsToRemove:
logging.info('Removing contestant group: %s', group)
client.contest.removeGroup(contest_alias=alias, group=group)
logging.info("Successfully upserted contest %s", title)