Import pygrader, instead of pygrader.ENCODING.
[pygrader.git] / pygrader / storage.py
1 # Copyright (C) 2012 W. Trevor King <wking@tremily.us>
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 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
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     >>> stub_course.cleanup()
58     """
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']:
66         names[option] = [
67         a.strip() for a in config.get('course', option).split(',')]
68     assignments = []
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))))
73     people = {}
74     for group in ['robot', 'professors', 'assistants', 'students']:
75         for person in names[group]:
76             if person in people:
77                 _LOG.debug('adding person {} to group {}'.format(
78                         person, group))
79                 people[person].groups.append(group)
80             else:
81                 _LOG.debug('loading person {} in group {}'.format(
82                         person, group))
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))
89     return _Course(
90         name=name, assignments=assignments, people=people, grades=grades,
91         robot=robot)
92
93 def parse_date(string):
94     """Parse dates given using the W3C DTF profile of ISO 8601.
95
96     The following are legal formats::
97
98       YYYY (e.g. 2000)
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)
104
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.
110
111     >>> import calendar
112     >>> import email.utils
113     >>> import time
114     >>> ref = calendar.timegm(time.strptime('2000', '%Y'))
115     >>> y = parse_date('2000')
116     >>> y - ref  # seconds between y and ref
117     0
118     >>> ym = parse_date('2000-02')
119     >>> (ym - y)/(3600.*24)  # days between ym and y
120     31.0
121     >>> ymd = parse_date('2000-02-12')
122     >>> (ymd - ym)/(3600.*24)  # days between ymd and ym
123     11.0
124     >>> ymdhm = parse_date('2000-02-12T06:05+05:30')
125     >>> (ymdhm - ymd)/60.  # minutes between ymdhm and ymd
126     35.0
127     >>> (ymdhm - parse_date('2000-02-12T06:05Z'))/3600.
128     -5.5
129     >>> ymdhms = parse_date('2000-02-12T06:05:30+05:30')
130     >>> ymdhms - ymdhm
131     30
132     >>> (ymdhms - parse_date('2000-02-12T06:05:30Z'))/3600.
133     -5.5
134     >>> ymdhms_ms = parse_date('2000-02-12T06:05:30.45+05:30')
135     >>> ymdhms_ms - ymdhms  # doctest: +ELLIPSIS
136     0.45000...
137     >>> (ymdhms_ms - parse_date('2000-02-12T06:05:30.45Z'))/3600.
138     -5.5
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')
143     0
144     """
145     m = _DATE_REGEXP.match(string)
146     if not m:
147         raise ValueError(string)
148     date,t,time,ms,zone = m.groups()
149     ret = None
150     if t:
151         date += 'T' + time
152     error = None
153     for fmt in ['%Y-%m-%dT%H:%M:%S',
154                 '%Y-%m-%dT%H:%M',
155                 '%Y-%m-%d',
156                 '%Y-%m',
157                 '%Y',
158                 ]:
159         try:
160             ret = _time.strptime(date, fmt)
161         except ValueError as e:
162             error = e
163         else:
164             break
165     if ret is None:
166         raise error
167     ret = list(ret)
168     ret[-1] = 0  # don't use daylight savings time
169     ret = _calendar.timegm(ret)
170     if ms:
171         ret += float(ms)
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)
176         ret -= offset
177     return ret
178
179 def parse_boolean(value):
180     """Convert a boolean string into ``True`` or ``False``.
181
182     Supports the same values as ``RawConfigParser``
183
184     >>> parse_boolean('YES')
185     True
186     >>> parse_boolean('Yes')
187     True
188     >>> parse_boolean('tRuE')
189     True
190     >>> parse_boolean('False')
191     False
192     >>> parse_boolean('FALSE')
193     False
194     >>> parse_boolean('no')
195     False
196     >>> parse_boolean('none')
197     Traceback (most recent call last):
198       ...
199     ValueError: Not a boolean: none
200     >>> parse_boolean('')  # doctest: +NORMALIZE_WHITESPACE
201     Traceback (most recent call last):
202       ...
203     ValueError: Not a boolean:
204
205     It passes through boolean inputs without modification (so you
206     don't have to use strings for default values):
207
208     >>> parse_boolean({}.get('my-option', True))
209     True
210     >>> parse_boolean({}.get('my-option', False))
211     False
212     """
213     if value in [True, False]:
214         return value
215     # Using an underscored method is hackish, but it should be fairly stable.
216     p = _configparser.RawConfigParser()
217     return p._convert_to_boolean(value)
218
219 def load_assignment(name, data):
220     r"""Load an assignment from a ``dict``
221
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',
229     ...           })
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
235     """
236     points = int(data['points'])
237     wterms = data['weight'].split('/')
238     if len(wterms) == 1:
239         weight = float(wterms[0])
240     else:
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))
245     return _Assignment(
246         name=name, points=points, weight=weight, due=due,
247         submittable=submittable)
248
249 def load_person(name, data={}):
250     r"""Load a person from a ``dict``
251
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>
257     ... ''')
258
259     >>> p = load_person(
260     ...     name='Gandalf',
261     ...     data={'nickname': 'G-Man',
262     ...           'emails': 'g@grey.edu, g@greyhavens.net',
263     ...           'pgp-key': '0x0123456789ABCDEF',
264     ...           })
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))
269     Gandalf: None | None
270     """
271     kwargs = {}
272     emails = [x.strip() for x in data.get('emails', '').split(',')]
273     emails = list(filter(bool, emails))  # remove blank emails
274     if emails:
275         kwargs['emails'] = emails
276     nickname = data.get('nickname', None)
277     if nickname:
278         kwargs['aliases'] = [nickname]
279     pgp_key = data.get('pgp-key', None)
280     if pgp_key:
281         kwargs['pgp_key'] = pgp_key
282     return _Person(name=name, **kwargs)
283
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:
288             try:
289                 yield load_grade(basedir, assignment, person)
290             except IOError:
291                 continue
292
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),
299                     assignment, person)
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)
305     else:
306         g.notified = False
307     return g
308
309 def parse_grade(stream, assignment, person):
310     "Parse the points and comment from a grade stream."
311     try:
312         points = float(stream.readline())
313     except ValueError:
314         _sys.stderr.write('failure reading {}, {}\n'.format(
315                 assignment.name, person.name))
316         raise
317     comment = stream.read().strip() or None
318     return _Grade(
319         student=person, assignment=assignment, points=points, comment=comment)
320
321 def assignment_path(basedir, assignment, person):
322     return _os_path.join(basedir,
323                   _filesystem_name(person.name),
324                   _filesystem_name(assignment.name))
325
326 def _filesystem_name(name):
327     for a,b in [(' ', '_'), ('.', ''), ("'", ''), ('"', '')]:
328         name = name.replace(a, b)
329     return name
330
331 def set_notified(basedir, grade):
332     """Mark `grade.student` as notified about `grade`
333     """
334     path = assignment_path(
335         basedir=basedir, assignment=grade.assignment, person=grade.student)
336     npath = _os_path.join(path, 'notified')
337     _touch(npath)
338
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')
343     _touch(Lpath)
344
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):
350         _os.makedirs(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))
354         if grade.comment:
355             f.write('\n{}\n'.format(grade.comment.strip()))
356     set_notified(basedir=basedir, grade=grade)
357     set_late(
358         basedir=basedir, assignment=grade.assignment, person=grade.student)
359
360 def _touch(path):
361     """Touch a file (`path` is created if it doesn't already exist)
362
363     Also updates the access and modification times to the current
364     time.
365
366     >>> from os import listdir, rmdir, unlink
367     >>> from os.path import join
368     >>> from tempfile import mkdtemp
369     >>> d = mkdtemp(prefix='pygrader')
370     >>> listdir(d)
371     []
372     >>> p = join(d, 'touched')
373     >>> _touch(p)
374     >>> listdir(d)
375     ['touched']
376     >>> _touch(p)
377     >>> unlink(p)
378     >>> rmdir(d)
379     """
380     with open(path, 'a') as f:
381         pass
382     _os.utime(path, None)
383
384 def initialize(basedir, course, dry_run=False, **kwargs):
385     """Stub out the directory tree based on the course configuration.
386     """
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))
393             else:
394                 try:
395                     _os.makedirs(path)
396                 except OSError:
397                     continue
398                 else:
399                     _LOG.debug('creating {}'.format(path))