1 # Copyright (C) 2012 W. Trevor King <wking@tremily.us>
3 # This file is part of pygrader.
5 # pygrader is free software: you can redistribute it and/or modify it under the
6 # terms of the GNU General Public License as published by the Free Software
7 # Foundation, either version 3 of the License, or (at your option) any later
10 # pygrader is distributed in the hope that it will be useful, but WITHOUT ANY
11 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
14 # You should have received a copy of the GNU General Public License along with
15 # pygrader. If not, see <http://www.gnu.org/licenses/>.
17 from __future__ import absolute_import
19 import calendar as _calendar
20 import configparser as _configparser
21 import email.utils as _email_utils
24 import os.path as _os_path
29 from . import LOG as _LOG
30 from . import ENCODING as _ENCODING
31 from .model.assignment import Assignment as _Assignment
32 from .model.course import Course as _Course
33 from .model.grade import Grade as _Grade
34 from .model.person import Person as _Person
35 from .todo import newer
38 _DATE_REGEXP = _re.compile('^([^T]*)(T?)([^TZ+-.]*)([.]?[0-9]*)([+-][0-9:]*|Z?)$')
41 def load_course(basedir):
42 """Load a course directory.
44 >>> from pygrader.test.course import StubCourse
45 >>> stub_course = StubCourse(load=False)
46 >>> course = load_course(basedir=stub_course.basedir)
49 >>> course.assignments # doctest: +ELLIPSIS
50 [<pygrader.model.assignment.Assignment object at 0x...>, ...]
51 >>> course.people # doctest: +ELLIPSIS
52 [<pygrader.model.person.Person object at 0x...>, ...]
55 >>> print(course.robot)
57 >>> stub_course.cleanup()
59 _LOG.debug('loading course from {}'.format(basedir))
60 config = _configparser.ConfigParser()
61 config.read([_os_path.join(basedir, 'course.conf')])
62 name = config.get('course', 'name')
63 names = {'robot': [config.get('course', 'robot').strip()]}
64 for option in ['assignments', 'professors', 'assistants', 'students']:
66 a.strip() for a in config.get('course', option).split(',')]
68 for assignment in names['assignments']:
69 _LOG.debug('loading assignment {}'.format(assignment))
70 assignments.append(load_assignment(
71 name=assignment, data=dict(config.items(assignment))))
73 for group in ['robot', 'professors', 'assistants', 'students']:
74 for person in names[group]:
76 _LOG.debug('adding person {} to group {}'.format(
78 people[person].groups.append(group)
80 _LOG.debug('loading person {} in group {}'.format(
82 people[person] = load_person(
83 name=person, data=dict(config.items(person)))
84 people[person].groups = [group]
85 people = people.values()
86 robot = [p for p in people if 'robot' in p.groups][0]
87 grades = list(load_grades(basedir, assignments, people))
89 name=name, assignments=assignments, people=people, grades=grades,
92 def parse_date(string):
93 """Parse dates given using the W3C DTF profile of ISO 8601.
95 The following are legal formats::
98 YYYY-MM (e.g. 2000-02)
99 YYYY-MM-DD (e.g. 2000-02-12)
100 YYYY-MM-DDThh:mmTZD (e.g. 2000-02-12T06:05+05:30)
101 YYYY-MM-DDThh:mm:ssTZD (e.g. 2000-02-12T06:05:30+05:30)
102 YYYY-MM-DDThh:mm:ss.sTZD (e.g. 2000-02-12T06:05:30.45+05:30)
104 Note that the TZD can be either the capital letter `Z` to indicate
105 UTC time, a string in the format +hh:mm to indicate a local time
106 expressed with a time zone hh hours and mm minutes ahead of UTC or
107 -hh:mm to indicate a local time expressed with a time zone hh
108 hours and mm minutes behind UTC.
111 >>> import email.utils
113 >>> ref = calendar.timegm(time.strptime('2000', '%Y'))
114 >>> y = parse_date('2000')
115 >>> y - ref # seconds between y and ref
117 >>> ym = parse_date('2000-02')
118 >>> (ym - y)/(3600.*24) # days between ym and y
120 >>> ymd = parse_date('2000-02-12')
121 >>> (ymd - ym)/(3600.*24) # days between ymd and ym
123 >>> ymdhm = parse_date('2000-02-12T06:05+05:30')
124 >>> (ymdhm - ymd)/60. # minutes between ymdhm and ymd
126 >>> (ymdhm - parse_date('2000-02-12T06:05Z'))/3600.
128 >>> ymdhms = parse_date('2000-02-12T06:05:30+05:30')
131 >>> (ymdhms - parse_date('2000-02-12T06:05:30Z'))/3600.
133 >>> ymdhms_ms = parse_date('2000-02-12T06:05:30.45+05:30')
134 >>> ymdhms_ms - ymdhms # doctest: +ELLIPSIS
136 >>> (ymdhms_ms - parse_date('2000-02-12T06:05:30.45Z'))/3600.
138 >>> p = parse_date('1994-11-05T08:15:30-05:00')
139 >>> email.utils.formatdate(p, localtime=True)
140 'Sat, 05 Nov 1994 08:15:30 -0500'
141 >>> p - parse_date('1994-11-05T13:15:30Z')
144 m = _DATE_REGEXP.match(string)
146 raise ValueError(string)
147 date,t,time,ms,zone = m.groups()
152 for fmt in ['%Y-%m-%dT%H:%M:%S',
159 ret = _time.strptime(date, fmt)
160 except ValueError as e:
167 ret[-1] = 0 # don't use daylight savings time
168 ret = _calendar.timegm(ret)
171 if zone and zone != 'Z':
172 sign = int(zone[1] + '1')
173 hour,minute = map(int, zone.split(':', 1))
174 offset = sign*(3600*hour + 60*minute)
178 def parse_boolean(value):
179 """Convert a boolean string into ``True`` or ``False``.
181 Supports the same values as ``RawConfigParser``
183 >>> parse_boolean('YES')
185 >>> parse_boolean('Yes')
187 >>> parse_boolean('tRuE')
189 >>> parse_boolean('False')
191 >>> parse_boolean('FALSE')
193 >>> parse_boolean('no')
195 >>> parse_boolean('none')
196 Traceback (most recent call last):
198 ValueError: Not a boolean: none
199 >>> parse_boolean('') # doctest: +NORMALIZE_WHITESPACE
200 Traceback (most recent call last):
202 ValueError: Not a boolean:
204 It passes through boolean inputs without modification (so you
205 don't have to use strings for default values):
207 >>> parse_boolean({}.get('my-option', True))
209 >>> parse_boolean({}.get('my-option', False))
212 if value in [True, False]:
214 # Using an underscored method is hackish, but it should be fairly stable.
215 p = _configparser.RawConfigParser()
216 return p._convert_to_boolean(value)
218 def load_assignment(name, data):
219 r"""Load an assignment from a ``dict``
221 >>> from email.utils import formatdate
222 >>> a = load_assignment(
223 ... name='Attendance 1',
224 ... data={'points': '1',
225 ... 'weight': '0.1/2',
226 ... 'due': '2011-10-04T00:00-04:00',
227 ... 'submittable': 'yes',
229 >>> print(('{0.name} (points: {0.points}, weight: {0.weight}, '
230 ... 'due: {0.due}, submittable: {0.submittable})').format(a))
231 Attendance 1 (points: 1, weight: 0.05, due: 1317700800, submittable: True)
232 >>> print(formatdate(a.due, localtime=True))
233 Tue, 04 Oct 2011 00:00:00 -0400
235 points = int(data['points'])
236 wterms = data['weight'].split('/')
238 weight = float(wterms[0])
240 assert len(wterms) == 2, wterms
241 weight = float(wterms[0])/float(wterms[1])
242 due = parse_date(data['due'])
243 submittable = parse_boolean(data.get('submittable', False))
245 name=name, points=points, weight=weight, due=due,
246 submittable=submittable)
248 def load_person(name, data={}):
249 r"""Load a person from a ``dict``
251 >>> from io import StringIO
252 >>> stream = StringIO('''#comment line
253 ... Tom Bombadil <tbomb@oldforest.net> # post address comment
254 ... Tom Bombadil <yellow.boots@oldforest.net>
255 ... Goldberry <gb@oldforest.net>
260 ... data={'nickname': 'G-Man',
261 ... 'emails': 'g@grey.edu, g@greyhavens.net',
262 ... 'pgp-key': '0x0123456789ABCDEF',
264 >>> print('{0.name}: {0.emails} | {0.pgp_key}'.format(p))
265 Gandalf: ['g@grey.edu', 'g@greyhavens.net'] | 0x0123456789ABCDEF
266 >>> p = load_person(name='Gandalf')
267 >>> print('{0.name}: {0.emails} | {0.pgp_key}'.format(p))
271 emails = [x.strip() for x in data.get('emails', '').split(',')]
272 emails = list(filter(bool, emails)) # remove blank emails
274 kwargs['emails'] = emails
275 nickname = data.get('nickname', None)
277 kwargs['aliases'] = [nickname]
278 pgp_key = data.get('pgp-key', None)
280 kwargs['pgp_key'] = pgp_key
281 return _Person(name=name, **kwargs)
283 def load_grades(basedir, assignments, people):
284 "Load all grades in a course directory."
285 for assignment in assignments:
286 for person in people:
288 yield load_grade(basedir, assignment, person)
292 def load_grade(basedir, assignment, person):
293 "Load a single grade from a course directory."
294 _LOG.debug('loading {} grade for {}'.format(assignment, person))
295 path = assignment_path(basedir, assignment, person)
296 gpath = _os_path.join(path, 'grade')
297 g = parse_grade(_io.open(gpath, 'r', encoding=_ENCODING),
299 #g.late = _os.stat(gpath).st_mtime > assignment.due
300 g.late = _os_path.exists(_os_path.join(path, 'late'))
301 npath = _os_path.join(path, 'notified')
302 if _os_path.exists(npath):
303 g.notified = newer(npath, gpath)
308 def parse_grade(stream, assignment, person):
309 "Parse the points and comment from a grade stream."
311 points = float(stream.readline())
313 _sys.stderr.write('failure reading {}, {}\n'.format(
314 assignment.name, person.name))
316 comment = stream.read().strip() or None
318 student=person, assignment=assignment, points=points, comment=comment)
320 def assignment_path(basedir, assignment, person):
321 return _os_path.join(basedir,
322 _filesystem_name(person.name),
323 _filesystem_name(assignment.name))
325 def _filesystem_name(name):
326 for a,b in [(' ', '_'), ('.', ''), ("'", ''), ('"', '')]:
327 name = name.replace(a, b)
330 def set_notified(basedir, grade):
331 """Mark `grade.student` as notified about `grade`
333 path = assignment_path(
334 basedir=basedir, assignment=grade.assignment, person=grade.student)
335 npath = _os_path.join(path, 'notified')
338 def set_late(basedir, assignment, person):
339 path = assignment_path(
340 basedir=basedir, assignment=assignment, person=person)
341 Lpath = _os_path.join(path, 'late')
344 def save_grade(basedir, grade):
345 "Save a grade into a course directory"
346 path = assignment_path(
347 basedir=basedir, assignment=grade.assignment, person=grade.student)
348 if not _os_path.isdir(path):
350 gpath = _os_path.join(path, 'grade')
351 with _io.open(gpath, 'w', encoding=_ENCODING) as f:
352 f.write('{}\n'.format(grade.points))
354 f.write('\n{}\n'.format(grade.comment.strip()))
355 set_notified(basedir=basedir, grade=grade)
357 basedir=basedir, assignment=grade.assignment, person=grade.student)
360 """Touch a file (`path` is created if it doesn't already exist)
362 Also updates the access and modification times to the current
365 >>> from os import listdir, rmdir, unlink
366 >>> from os.path import join
367 >>> from tempfile import mkdtemp
368 >>> d = mkdtemp(prefix='pygrader')
371 >>> p = join(d, 'touched')
379 with open(path, 'a') as f:
381 _os.utime(path, None)
383 def initialize(basedir, course, dry_run=False, **kwargs):
384 """Stub out the directory tree based on the course configuration.
386 for person in course.people:
387 for assignment in course.assignments:
388 path = assignment_path(basedir, assignment, person)
389 if dry_run: # we'll need to guess if mkdirs would work
390 if not _os_path.exists(path):
391 _LOG.debug('creating {}'.format(path))
398 _LOG.debug('creating {}'.format(path))