1 # Copyright (C) 2012 W. Trevor King <wking@drexel.edu>
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)
58 _LOG.debug('loading course from {}'.format(basedir))
59 config = _configparser.ConfigParser()
60 config.read([_os_path.join(basedir, 'course.conf')])
61 name = config.get('course', 'name')
62 names = {'robot': [config.get('course', 'robot').strip()]}
63 for option in ['assignments', 'professors', 'assistants', 'students']:
65 a.strip() for a in config.get('course', option).split(',')]
67 for assignment in names['assignments']:
68 _LOG.debug('loading assignment {}'.format(assignment))
69 assignments.append(load_assignment(
70 name=assignment, data=dict(config.items(assignment))))
72 for group in ['robot', 'professors', 'assistants', 'students']:
73 for person in names[group]:
75 _LOG.debug('adding person {} to group {}'.format(
77 people[person].groups.append(group)
79 _LOG.debug('loading person {} in group {}'.format(
81 people[person] = load_person(
82 name=person, data=dict(config.items(person)))
83 people[person].groups = [group]
84 people = people.values()
85 robot = [p for p in people if 'robot' in p.groups][0]
86 grades = list(load_grades(basedir, assignments, people))
88 name=name, assignments=assignments, people=people, grades=grades,
91 def parse_date(string):
92 """Parse dates given using the W3C DTF profile of ISO 8601.
94 The following are legal formats::
97 YYYY-MM (e.g. 2000-02)
98 YYYY-MM-DD (e.g. 2000-02-12)
99 YYYY-MM-DDThh:mmTZD (e.g. 2000-02-12T06:05+05:30)
100 YYYY-MM-DDThh:mm:ssTZD (e.g. 2000-02-12T06:05:30+05:30)
101 YYYY-MM-DDThh:mm:ss.sTZD (e.g. 2000-02-12T06:05:30.45+05:30)
103 Note that the TZD can be either the capital letter `Z` to indicate
104 UTC time, a string in the format +hh:mm to indicate a local time
105 expressed with a time zone hh hours and mm minutes ahead of UTC or
106 -hh:mm to indicate a local time expressed with a time zone hh
107 hours and mm minutes behind UTC.
110 >>> import email.utils
112 >>> ref = calendar.timegm(time.strptime('2000', '%Y'))
113 >>> y = parse_date('2000')
114 >>> y - ref # seconds between y and ref
116 >>> ym = parse_date('2000-02')
117 >>> (ym - y)/(3600.*24) # days between ym and y
119 >>> ymd = parse_date('2000-02-12')
120 >>> (ymd - ym)/(3600.*24) # days between ymd and ym
122 >>> ymdhm = parse_date('2000-02-12T06:05+05:30')
123 >>> (ymdhm - ymd)/60. # minutes between ymdhm and ymd
125 >>> (ymdhm - parse_date('2000-02-12T06:05Z'))/3600.
127 >>> ymdhms = parse_date('2000-02-12T06:05:30+05:30')
130 >>> (ymdhms - parse_date('2000-02-12T06:05:30Z'))/3600.
132 >>> ymdhms_ms = parse_date('2000-02-12T06:05:30.45+05:30')
133 >>> ymdhms_ms - ymdhms # doctest: +ELLIPSIS
135 >>> (ymdhms_ms - parse_date('2000-02-12T06:05:30.45Z'))/3600.
137 >>> p = parse_date('1994-11-05T08:15:30-05:00')
138 >>> email.utils.formatdate(p, localtime=True)
139 'Sat, 05 Nov 1994 08:15:30 -0500'
140 >>> p - parse_date('1994-11-05T13:15:30Z')
143 m = _DATE_REGEXP.match(string)
145 raise ValueError(string)
146 date,t,time,ms,zone = m.groups()
151 for fmt in ['%Y-%m-%dT%H:%M:%S',
158 ret = _time.strptime(date, fmt)
159 except ValueError as e:
166 ret[-1] = 0 # don't use daylight savings time
167 ret = _calendar.timegm(ret)
170 if zone and zone != 'Z':
171 sign = int(zone[1] + '1')
172 hour,minute = map(int, zone.split(':', 1))
173 offset = sign*(3600*hour + 60*minute)
177 def load_assignment(name, data):
178 r"""Load an assignment from a ``dict``
180 >>> from email.utils import formatdate
181 >>> a = load_assignment(
182 ... name='Attendance 1',
183 ... data={'points': '1',
184 ... 'weight': '0.1/2',
185 ... 'due': '2011-10-04T00:00-04:00',
187 >>> print('{0.name} (points: {0.points}, weight: {0.weight}, due: {0.due})'.format(a))
188 Attendance 1 (points: 1, weight: 0.05, due: 1317700800)
189 >>> print(formatdate(a.due, localtime=True))
190 Tue, 04 Oct 2011 00:00:00 -0400
192 points = int(data['points'])
193 wterms = data['weight'].split('/')
195 weight = float(wterms[0])
197 assert len(wterms) == 2, wterms
198 weight = float(wterms[0])/float(wterms[1])
199 due = parse_date(data['due'])
200 return _Assignment(name=name, points=points, weight=weight, due=due)
202 def load_person(name, data={}):
203 r"""Load a person from a ``dict``
205 >>> from io import StringIO
206 >>> stream = StringIO('''#comment line
207 ... Tom Bombadil <tbomb@oldforest.net> # post address comment
208 ... Tom Bombadil <yellow.boots@oldforest.net>
209 ... Goldberry <gb@oldforest.net>
214 ... data={'nickname': 'G-Man',
215 ... 'emails': 'g@grey.edu, g@greyhavens.net',
216 ... 'pgp-key': '0x0123456789ABCDEF',
218 >>> print('{0.name}: {0.emails} | {0.pgp_key}'.format(p))
219 Gandalf: ['g@grey.edu', 'g@greyhavens.net'] | 0x0123456789ABCDEF
220 >>> p = load_person(name='Gandalf')
221 >>> print('{0.name}: {0.emails} | {0.pgp_key}'.format(p))
225 emails = [x.strip() for x in data.get('emails', '').split(',')]
226 emails = list(filter(bool, emails)) # remove blank emails
228 kwargs['emails'] = emails
229 nickname = data.get('nickname', None)
231 kwargs['aliases'] = [nickname]
232 pgp_key = data.get('pgp-key', None)
234 kwargs['pgp_key'] = pgp_key
235 return _Person(name=name, **kwargs)
237 def load_grades(basedir, assignments, people):
238 for assignment in assignments:
239 for person in people:
240 _LOG.debug('loading {} grade for {}'.format(assignment, person))
241 path = assignment_path(basedir, assignment, person)
242 gpath = _os_path.join(path, 'grade')
244 g = _load_grade(_io.open(gpath, 'r', encoding=_ENCODING),
248 #g.late = _os.stat(gpath).st_mtime > assignment.due
249 g.late = _os_path.exists(_os_path.join(path, 'late'))
250 npath = _os_path.join(path, 'notified')
251 if _os_path.exists(npath):
252 g.notified = newer(npath, gpath)
257 def _load_grade(stream, assignment, person):
259 points = float(stream.readline())
261 _sys.stderr.write('failure reading {}, {}\n'.format(
262 assignment.name, person.name))
264 comment = stream.read().strip() or None
266 student=person, assignment=assignment, points=points, comment=comment)
268 def assignment_path(basedir, assignment, person):
269 return _os_path.join(basedir,
270 _filesystem_name(person.name),
271 _filesystem_name(assignment.name))
273 def _filesystem_name(name):
274 for a,b in [(' ', '_'), ('.', ''), ("'", ''), ('"', '')]:
275 name = name.replace(a, b)
278 def set_notified(basedir, grade):
279 """Mark `grade.student` as notified about `grade`
281 path = assignment_path(
282 basedir=basedir, assignment=grade.assignment, person=grade.student)
283 npath = _os_path.join(path, 'notified')
286 def set_late(basedir, assignment, person):
287 path = assignment_path(
288 basedir=basedir, assignment=assignment, person=person)
289 Lpath = _os_path.join(path, 'late')
293 """Touch a file (`path` is created if it doesn't already exist)
295 Also updates the access and modification times to the current
298 >>> from os import listdir, rmdir, unlink
299 >>> from os.path import join
300 >>> from tempfile import mkdtemp
301 >>> d = mkdtemp(prefix='pygrader')
304 >>> p = join(d, 'touched')
312 with open(path, 'a') as f:
314 _os.utime(path, None)
316 def initialize(basedir, course, dry_run=False, **kwargs):
317 """Stub out the directory tree based on the course configuration.
319 for person in course.people:
320 for assignment in course.assignments:
321 path = assignment_path(basedir, assignment, person)
322 if dry_run: # we'll need to guess if mkdirs would work
323 if not _os_path.exists(path):
324 _LOG.debug('creating {}'.format(path))
331 _LOG.debug('creating {}'.format(path))