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 import pygrader as _pygrader
30 from . import LOG as _LOG
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 encoding=_pygrader.ENCODING)
63 name = config.get('course', 'name')
64 names = {'robot': [config.get('course', 'robot').strip()]}
65 for option in ['assignments', 'professors', 'assistants', 'students']:
67 a.strip() for a in config.get('course', option).split(',')]
69 for assignment in names['assignments']:
70 _LOG.debug('loading assignment {}'.format(assignment))
71 assignments.append(load_assignment(
72 name=assignment, data=dict(config.items(assignment))))
74 for group in ['robot', 'professors', 'assistants', 'students']:
75 for person in names[group]:
77 _LOG.debug('adding person {} to group {}'.format(
79 people[person].groups.append(group)
81 _LOG.debug('loading person {} in group {}'.format(
83 people[person] = load_person(
84 name=person, data=dict(config.items(person)))
85 people[person].groups = [group]
86 people = people.values()
87 robot = [p for p in people if 'robot' in p.groups][0]
88 grades = list(load_grades(basedir, assignments, people))
90 name=name, assignments=assignments, people=people, grades=grades,
93 def parse_date(string):
94 """Parse dates given using the W3C DTF profile of ISO 8601.
96 The following are legal formats::
99 YYYY-MM (e.g. 2000-02)
100 YYYY-MM-DD (e.g. 2000-02-12)
101 YYYY-MM-DDThh:mmTZD (e.g. 2000-02-12T06:05+05:30)
102 YYYY-MM-DDThh:mm:ssTZD (e.g. 2000-02-12T06:05:30+05:30)
103 YYYY-MM-DDThh:mm:ss.sTZD (e.g. 2000-02-12T06:05:30.45+05:30)
105 Note that the TZD can be either the capital letter `Z` to indicate
106 UTC time, a string in the format +hh:mm to indicate a local time
107 expressed with a time zone hh hours and mm minutes ahead of UTC or
108 -hh:mm to indicate a local time expressed with a time zone hh
109 hours and mm minutes behind UTC.
112 >>> import email.utils
114 >>> ref = calendar.timegm(time.strptime('2000', '%Y'))
115 >>> y = parse_date('2000')
116 >>> y - ref # seconds between y and ref
118 >>> ym = parse_date('2000-02')
119 >>> (ym - y)/(3600.*24) # days between ym and y
121 >>> ymd = parse_date('2000-02-12')
122 >>> (ymd - ym)/(3600.*24) # days between ymd and ym
124 >>> ymdhm = parse_date('2000-02-12T06:05+05:30')
125 >>> (ymdhm - ymd)/60. # minutes between ymdhm and ymd
127 >>> (ymdhm - parse_date('2000-02-12T06:05Z'))/3600.
129 >>> ymdhms = parse_date('2000-02-12T06:05:30+05:30')
132 >>> (ymdhms - parse_date('2000-02-12T06:05:30Z'))/3600.
134 >>> ymdhms_ms = parse_date('2000-02-12T06:05:30.45+05:30')
135 >>> ymdhms_ms - ymdhms # doctest: +ELLIPSIS
137 >>> (ymdhms_ms - parse_date('2000-02-12T06:05:30.45Z'))/3600.
139 >>> p = parse_date('1994-11-05T08:15:30-05:00')
140 >>> email.utils.formatdate(p, localtime=True)
141 'Sat, 05 Nov 1994 08:15:30 -0500'
142 >>> p - parse_date('1994-11-05T13:15:30Z')
145 m = _DATE_REGEXP.match(string)
147 raise ValueError(string)
148 date,t,time,ms,zone = m.groups()
153 for fmt in ['%Y-%m-%dT%H:%M:%S',
160 ret = _time.strptime(date, fmt)
161 except ValueError as e:
168 ret[-1] = 0 # don't use daylight savings time
169 ret = _calendar.timegm(ret)
172 if zone and zone != 'Z':
173 sign = int(zone[1] + '1')
174 hour,minute = map(int, zone.split(':', 1))
175 offset = sign*(3600*hour + 60*minute)
179 def parse_boolean(value):
180 """Convert a boolean string into ``True`` or ``False``.
182 Supports the same values as ``RawConfigParser``
184 >>> parse_boolean('YES')
186 >>> parse_boolean('Yes')
188 >>> parse_boolean('tRuE')
190 >>> parse_boolean('False')
192 >>> parse_boolean('FALSE')
194 >>> parse_boolean('no')
196 >>> parse_boolean('none')
197 Traceback (most recent call last):
199 ValueError: Not a boolean: none
200 >>> parse_boolean('') # doctest: +NORMALIZE_WHITESPACE
201 Traceback (most recent call last):
203 ValueError: Not a boolean:
205 It passes through boolean inputs without modification (so you
206 don't have to use strings for default values):
208 >>> parse_boolean({}.get('my-option', True))
210 >>> parse_boolean({}.get('my-option', False))
213 if value in [True, False]:
215 # Using an underscored method is hackish, but it should be fairly stable.
216 p = _configparser.RawConfigParser()
217 return p._convert_to_boolean(value)
219 def load_assignment(name, data):
220 r"""Load an assignment from a ``dict``
222 >>> from email.utils import formatdate
223 >>> a = load_assignment(
224 ... name='Attendance 1',
225 ... data={'points': '1',
226 ... 'weight': '0.1/2',
227 ... 'due': '2011-10-04T00:00-04:00',
228 ... 'submittable': 'yes',
230 >>> print(('{0.name} (points: {0.points}, weight: {0.weight}, '
231 ... 'due: {0.due}, submittable: {0.submittable})').format(a))
232 Attendance 1 (points: 1, weight: 0.05, due: 1317700800, submittable: True)
233 >>> print(formatdate(a.due, localtime=True))
234 Tue, 04 Oct 2011 00:00:00 -0400
236 points = int(data['points'])
237 wterms = data['weight'].split('/')
239 weight = float(wterms[0])
241 assert len(wterms) == 2, wterms
242 weight = float(wterms[0])/float(wterms[1])
243 due = parse_date(data['due'])
244 submittable = parse_boolean(data.get('submittable', False))
246 name=name, points=points, weight=weight, due=due,
247 submittable=submittable)
249 def load_person(name, data={}):
250 r"""Load a person from a ``dict``
252 >>> from io import StringIO
253 >>> stream = StringIO('''#comment line
254 ... Tom Bombadil <tbomb@oldforest.net> # post address comment
255 ... Tom Bombadil <yellow.boots@oldforest.net>
256 ... Goldberry <gb@oldforest.net>
261 ... data={'nickname': 'G-Man',
262 ... 'emails': 'g@grey.edu, g@greyhavens.net',
263 ... 'pgp-key': '0x0123456789ABCDEF',
265 >>> print('{0.name}: {0.emails} | {0.pgp_key}'.format(p))
266 Gandalf: ['g@grey.edu', 'g@greyhavens.net'] | 0x0123456789ABCDEF
267 >>> p = load_person(name='Gandalf')
268 >>> print('{0.name}: {0.emails} | {0.pgp_key}'.format(p))
272 emails = [x.strip() for x in data.get('emails', '').split(',')]
273 emails = list(filter(bool, emails)) # remove blank emails
275 kwargs['emails'] = emails
276 nickname = data.get('nickname', None)
278 kwargs['aliases'] = [nickname]
279 pgp_key = data.get('pgp-key', None)
281 kwargs['pgp_key'] = pgp_key
282 return _Person(name=name, **kwargs)
284 def load_grades(basedir, assignments, people):
285 "Load all grades in a course directory."
286 for assignment in assignments:
287 for person in people:
289 yield load_grade(basedir, assignment, person)
293 def load_grade(basedir, assignment, person):
294 "Load a single grade from a course directory."
295 _LOG.debug('loading {} grade for {}'.format(assignment, person))
296 path = assignment_path(basedir, assignment, person)
297 gpath = _os_path.join(path, 'grade')
298 g = parse_grade(_io.open(gpath, 'r', encoding=_pygrader.ENCODING),
300 #g.late = _os.stat(gpath).st_mtime > assignment.due
301 g.late = _os_path.exists(_os_path.join(path, 'late'))
302 npath = _os_path.join(path, 'notified')
303 if _os_path.exists(npath):
304 g.notified = newer(npath, gpath)
309 def parse_grade(stream, assignment, person):
310 "Parse the points and comment from a grade stream."
312 points = float(stream.readline())
314 _sys.stderr.write('failure reading {}, {}\n'.format(
315 assignment.name, person.name))
317 comment = stream.read().strip() or None
319 student=person, assignment=assignment, points=points, comment=comment)
321 def assignment_path(basedir, assignment, person):
322 return _os_path.join(basedir,
323 _filesystem_name(person.name),
324 _filesystem_name(assignment.name))
326 def _filesystem_name(name):
327 for a,b in [(' ', '_'), ('.', ''), ("'", ''), ('"', '')]:
328 name = name.replace(a, b)
331 def set_notified(basedir, grade):
332 """Mark `grade.student` as notified about `grade`
334 path = assignment_path(
335 basedir=basedir, assignment=grade.assignment, person=grade.student)
336 npath = _os_path.join(path, 'notified')
339 def set_late(basedir, assignment, person):
340 path = assignment_path(
341 basedir=basedir, assignment=assignment, person=person)
342 Lpath = _os_path.join(path, 'late')
345 def save_grade(basedir, grade):
346 "Save a grade into a course directory"
347 path = assignment_path(
348 basedir=basedir, assignment=grade.assignment, person=grade.student)
349 if not _os_path.isdir(path):
351 gpath = _os_path.join(path, 'grade')
352 with _io.open(gpath, 'w', encoding=_pygrader.ENCODING) as f:
353 f.write('{}\n'.format(grade.points))
355 f.write('\n{}\n'.format(grade.comment.strip()))
356 set_notified(basedir=basedir, grade=grade)
358 basedir=basedir, assignment=grade.assignment, person=grade.student)
361 """Touch a file (`path` is created if it doesn't already exist)
363 Also updates the access and modification times to the current
366 >>> from os import listdir, rmdir, unlink
367 >>> from os.path import join
368 >>> from tempfile import mkdtemp
369 >>> d = mkdtemp(prefix='pygrader')
372 >>> p = join(d, 'touched')
380 with open(path, 'a') as f:
382 _os.utime(path, None)
384 def initialize(basedir, course, dry_run=False, **kwargs):
385 """Stub out the directory tree based on the course configuration.
387 for person in course.people:
388 for assignment in course.assignments:
389 path = assignment_path(basedir, assignment, person)
390 if dry_run: # we'll need to guess if mkdirs would work
391 if not _os_path.exists(path):
392 _LOG.debug('creating {}'.format(path))
399 _LOG.debug('creating {}'.format(path))