Finish mailpipe respond() doctests.
[pygrader.git] / pygrader / storage.py
1 # Copyright (C) 2012 W. Trevor King <wking@drexel.edu>
2 #
3 # This file is part of pygrader.
4 #
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
8 # version.
9 #
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.
13 #
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/>.
16
17 from __future__ import absolute_import
18
19 import calendar as _calendar
20 import configparser as _configparser
21 import email.utils as _email_utils
22 import io as _io
23 import os as _os
24 import os.path as _os_path
25 import re as _re
26 import sys as _sys
27 import time as _time
28
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
36
37
38 _DATE_REGEXP = _re.compile('^([^T]*)(T?)([^TZ+-.]*)([.]?[0-9]*)([+-][0-9:]*|Z?)$')
39
40
41 def load_course(basedir):
42     """Load a course directory.
43
44     >>> from pygrader.test.course import StubCourse
45     >>> stub_course = StubCourse(load=False)
46     >>> course = load_course(basedir=stub_course.basedir)
47     >>> course.name
48     'Physics 101'
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...>, ...]
53     >>> course.grades
54     []
55     >>> print(course.robot)
56     <Person Robot101>
57     """
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']:
64         names[option] = [
65         a.strip() for a in config.get('course', option).split(',')]
66     assignments = []
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))))
71     people = {}
72     for group in ['robot', 'professors', 'assistants', 'students']:
73         for person in names[group]:
74             if person in people:
75                 _LOG.debug('adding person {} to group {}'.format(
76                         person, group))
77                 people[person].groups.append(group)
78             else:
79                 _LOG.debug('loading person {} in group {}'.format(
80                         person, group))
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))
87     return _Course(
88         name=name, assignments=assignments, people=people, grades=grades,
89         robot=robot)
90
91 def parse_date(string):
92     """Parse dates given using the W3C DTF profile of ISO 8601.
93
94     The following are legal formats::
95
96       YYYY (e.g. 2000)
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)
102
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.
108
109     >>> import calendar
110     >>> import email.utils
111     >>> import time
112     >>> ref = calendar.timegm(time.strptime('2000', '%Y'))
113     >>> y = parse_date('2000')
114     >>> y - ref  # seconds between y and ref
115     0
116     >>> ym = parse_date('2000-02')
117     >>> (ym - y)/(3600.*24)  # days between ym and y
118     31.0
119     >>> ymd = parse_date('2000-02-12')
120     >>> (ymd - ym)/(3600.*24)  # days between ymd and ym
121     11.0
122     >>> ymdhm = parse_date('2000-02-12T06:05+05:30')
123     >>> (ymdhm - ymd)/60.  # minutes between ymdhm and ymd
124     35.0
125     >>> (ymdhm - parse_date('2000-02-12T06:05Z'))/3600.
126     -5.5
127     >>> ymdhms = parse_date('2000-02-12T06:05:30+05:30')
128     >>> ymdhms - ymdhm
129     30
130     >>> (ymdhms - parse_date('2000-02-12T06:05:30Z'))/3600.
131     -5.5
132     >>> ymdhms_ms = parse_date('2000-02-12T06:05:30.45+05:30')
133     >>> ymdhms_ms - ymdhms  # doctest: +ELLIPSIS
134     0.45000...
135     >>> (ymdhms_ms - parse_date('2000-02-12T06:05:30.45Z'))/3600.
136     -5.5
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')
141     0
142     """
143     m = _DATE_REGEXP.match(string)
144     if not m:
145         raise ValueError(string)
146     date,t,time,ms,zone = m.groups()
147     ret = None
148     if t:
149         date += 'T' + time
150     error = None
151     for fmt in ['%Y-%m-%dT%H:%M:%S',
152                 '%Y-%m-%dT%H:%M',
153                 '%Y-%m-%d',
154                 '%Y-%m',
155                 '%Y',
156                 ]:
157         try:
158             ret = _time.strptime(date, fmt)
159         except ValueError as e:
160             error = e
161         else:
162             break
163     if ret is None:
164         raise error
165     ret = list(ret)
166     ret[-1] = 0  # don't use daylight savings time
167     ret = _calendar.timegm(ret)
168     if ms:
169         ret += float(ms)
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)
174         ret -= offset
175     return ret
176
177 def parse_boolean(value):
178     """Convert a boolean string into ``True`` or ``False``.
179
180     Supports the same values as ``RawConfigParser``
181
182     >>> parse_boolean('YES')
183     True
184     >>> parse_boolean('Yes')
185     True
186     >>> parse_boolean('tRuE')
187     True
188     >>> parse_boolean('False')
189     False
190     >>> parse_boolean('FALSE')
191     False
192     >>> parse_boolean('no')
193     False
194     >>> parse_boolean('none')
195     Traceback (most recent call last):
196       ...
197     ValueError: Not a boolean: none
198     >>> parse_boolean('')  # doctest: +NORMALIZE_WHITESPACE
199     Traceback (most recent call last):
200       ...
201     ValueError: Not a boolean:
202
203     It passes through boolean inputs without modification (so you
204     don't have to use strings for default values):
205
206     >>> parse_boolean({}.get('my-option', True))
207     True
208     >>> parse_boolean({}.get('my-option', False))
209     False
210     """
211     if value in [True, False]:
212         return value
213     # Using an underscored method is hackish, but it should be fairly stable.
214     p = _configparser.RawConfigParser()
215     return p._convert_to_boolean(value)
216
217 def load_assignment(name, data):
218     r"""Load an assignment from a ``dict``
219
220     >>> from email.utils import formatdate
221     >>> a = load_assignment(
222     ...     name='Attendance 1',
223     ...     data={'points': '1',
224     ...           'weight': '0.1/2',
225     ...           'due': '2011-10-04T00:00-04:00',
226     ...           'submittable': 'yes',
227     ...           })
228     >>> print(('{0.name} (points: {0.points}, weight: {0.weight}, '
229     ...        'due: {0.due}, submittable: {0.submittable})').format(a))
230     Attendance 1 (points: 1, weight: 0.05, due: 1317700800, submittable: True)
231     >>> print(formatdate(a.due, localtime=True))
232     Tue, 04 Oct 2011 00:00:00 -0400
233     """
234     points = int(data['points'])
235     wterms = data['weight'].split('/')
236     if len(wterms) == 1:
237         weight = float(wterms[0])
238     else:
239         assert len(wterms) == 2, wterms
240         weight = float(wterms[0])/float(wterms[1])
241     due = parse_date(data['due'])
242     submittable = parse_boolean(data.get('submittable', False))
243     return _Assignment(
244         name=name, points=points, weight=weight, due=due,
245         submittable=submittable)
246
247 def load_person(name, data={}):
248     r"""Load a person from a ``dict``
249
250     >>> from io import StringIO
251     >>> stream = StringIO('''#comment line
252     ... Tom Bombadil <tbomb@oldforest.net>  # post address comment
253     ... Tom Bombadil <yellow.boots@oldforest.net>
254     ... Goldberry <gb@oldforest.net>
255     ... ''')
256
257     >>> p = load_person(
258     ...     name='Gandalf',
259     ...     data={'nickname': 'G-Man',
260     ...           'emails': 'g@grey.edu, g@greyhavens.net',
261     ...           'pgp-key': '0x0123456789ABCDEF',
262     ...           })
263     >>> print('{0.name}: {0.emails} | {0.pgp_key}'.format(p))
264     Gandalf: ['g@grey.edu', 'g@greyhavens.net'] | 0x0123456789ABCDEF
265     >>> p = load_person(name='Gandalf')
266     >>> print('{0.name}: {0.emails} | {0.pgp_key}'.format(p))
267     Gandalf: None | None
268     """
269     kwargs = {}
270     emails = [x.strip() for x in data.get('emails', '').split(',')]
271     emails = list(filter(bool, emails))  # remove blank emails
272     if emails:
273         kwargs['emails'] = emails
274     nickname = data.get('nickname', None)
275     if nickname:
276         kwargs['aliases'] = [nickname]
277     pgp_key = data.get('pgp-key', None)
278     if pgp_key:
279         kwargs['pgp_key'] = pgp_key
280     return _Person(name=name, **kwargs)
281
282 def load_grades(basedir, assignments, people):
283     for assignment in assignments:
284         for person in people:
285             _LOG.debug('loading {} grade for {}'.format(assignment, person))
286             path = assignment_path(basedir, assignment, person)
287             gpath = _os_path.join(path, 'grade')
288             try:
289                 g = _load_grade(_io.open(gpath, 'r', encoding=_ENCODING),
290                                 assignment, person)
291             except IOError:
292                 continue
293             #g.late = _os.stat(gpath).st_mtime > assignment.due
294             g.late = _os_path.exists(_os_path.join(path, 'late'))
295             npath = _os_path.join(path, 'notified')
296             if _os_path.exists(npath):
297                 g.notified = newer(npath, gpath)
298             else:
299                 g.notified = False
300             yield g
301
302 def _load_grade(stream, assignment, person):
303     try:
304         points = float(stream.readline())
305     except ValueError:
306         _sys.stderr.write('failure reading {}, {}\n'.format(
307                 assignment.name, person.name))
308         raise
309     comment = stream.read().strip() or None
310     return _Grade(
311         student=person, assignment=assignment, points=points, comment=comment)
312
313 def assignment_path(basedir, assignment, person):
314     return _os_path.join(basedir,
315                   _filesystem_name(person.name),
316                   _filesystem_name(assignment.name))
317
318 def _filesystem_name(name):
319     for a,b in [(' ', '_'), ('.', ''), ("'", ''), ('"', '')]:
320         name = name.replace(a, b)
321     return name
322
323 def set_notified(basedir, grade):
324     """Mark `grade.student` as notified about `grade`
325     """
326     path = assignment_path(
327         basedir=basedir, assignment=grade.assignment, person=grade.student)
328     npath = _os_path.join(path, 'notified')
329     _touch(npath)
330
331 def set_late(basedir, assignment, person):
332     path = assignment_path(
333         basedir=basedir, assignment=assignment, person=person)
334     Lpath = _os_path.join(path, 'late')
335     _touch(Lpath)
336
337 def _touch(path):
338     """Touch a file (`path` is created if it doesn't already exist)
339
340     Also updates the access and modification times to the current
341     time.
342
343     >>> from os import listdir, rmdir, unlink
344     >>> from os.path import join
345     >>> from tempfile import mkdtemp
346     >>> d = mkdtemp(prefix='pygrader')
347     >>> listdir(d)
348     []
349     >>> p = join(d, 'touched')
350     >>> _touch(p)
351     >>> listdir(d)
352     ['touched']
353     >>> _touch(p)
354     >>> unlink(p)
355     >>> rmdir(d)
356     """
357     with open(path, 'a') as f:
358         pass
359     _os.utime(path, None)
360
361 def initialize(basedir, course, dry_run=False, **kwargs):
362     """Stub out the directory tree based on the course configuration.
363     """
364     for person in course.people:
365         for assignment in course.assignments:
366             path = assignment_path(basedir, assignment, person)
367             if dry_run:  # we'll need to guess if mkdirs would work
368                 if not _os_path.exists(path):
369                     _LOG.debug('creating {}'.format(path))
370             else:
371                 try:
372                     _os.makedirs(path)
373                 except OSError:
374                     continue
375                 else:
376                     _LOG.debug('creating {}'.format(path))