7bc9a17d8bde544275b4ffacf6d2734c2c21a427
[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     'phys101'
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     """
56     _LOG.debug('loading course from {}'.format(basedir))
57     config = _configparser.ConfigParser()
58     config.read([_os_path.join(basedir, 'course.conf')])
59     name = config.get('course', 'name')
60     names = {}
61     for option in ['assignments', 'professors', 'assistants', 'students']:
62         names[option] = [
63         a.strip() for a in config.get('course', option).split(',')]
64     assignments = []
65     for assignment in names['assignments']:
66         _LOG.debug('loading assignment {}'.format(assignment))
67         assignments.append(load_assignment(
68                 name=assignment, data=dict(config.items(assignment))))
69     people = {}
70     for group in ['professors', 'assistants', 'students']:
71         for person in names[group]:
72             if person in people:
73                 _LOG.debug('adding person {} to group {}'.format(
74                         person, group))
75                 people[person].groups.append(group)
76             else:
77                 _LOG.debug('loading person {} in group {}'.format(
78                         person, group))
79                 people[person] = load_person(
80                     name=person, data=dict(config.items(person)))
81                 people[person].groups = [group]
82     people = people.values()
83     grades = list(load_grades(basedir, assignments, people))
84     return _Course(
85         name=name, assignments=assignments, people=people, grades=grades)
86
87 def parse_date(string):
88     """Parse dates given using the W3C DTF profile of ISO 8601.
89
90     The following are legal formats::
91
92       YYYY (e.g. 2000)
93       YYYY-MM (e.g. 2000-02)
94       YYYY-MM-DD (e.g. 2000-02-12)
95       YYYY-MM-DDThh:mmTZD (e.g. 2000-02-12T06:05+05:30)
96       YYYY-MM-DDThh:mm:ssTZD (e.g. 2000-02-12T06:05:30+05:30)
97       YYYY-MM-DDThh:mm:ss.sTZD (e.g. 2000-02-12T06:05:30.45+05:30)
98
99     Note that the TZD can be either the capital letter `Z` to indicate
100     UTC time, a string in the format +hh:mm to indicate a local time
101     expressed with a time zone hh hours and mm minutes ahead of UTC or
102     -hh:mm to indicate a local time expressed with a time zone hh
103     hours and mm minutes behind UTC.
104
105     >>> import calendar
106     >>> import email.utils
107     >>> import time
108     >>> ref = calendar.timegm(time.strptime('2000', '%Y'))
109     >>> y = parse_date('2000')
110     >>> y - ref  # seconds between y and ref
111     0
112     >>> ym = parse_date('2000-02')
113     >>> (ym - y)/(3600.*24)  # days between ym and y
114     31.0
115     >>> ymd = parse_date('2000-02-12')
116     >>> (ymd - ym)/(3600.*24)  # days between ymd and ym
117     11.0
118     >>> ymdhm = parse_date('2000-02-12T06:05+05:30')
119     >>> (ymdhm - ymd)/60.  # minutes between ymdhm and ymd
120     35.0
121     >>> (ymdhm - parse_date('2000-02-12T06:05Z'))/3600.
122     -5.5
123     >>> ymdhms = parse_date('2000-02-12T06:05:30+05:30')
124     >>> ymdhms - ymdhm
125     30
126     >>> (ymdhms - parse_date('2000-02-12T06:05:30Z'))/3600.
127     -5.5
128     >>> ymdhms_ms = parse_date('2000-02-12T06:05:30.45+05:30')
129     >>> ymdhms_ms - ymdhms  # doctest: +ELLIPSIS
130     0.45000...
131     >>> (ymdhms_ms - parse_date('2000-02-12T06:05:30.45Z'))/3600.
132     -5.5
133     >>> p = parse_date('1994-11-05T08:15:30-05:00')
134     >>> email.utils.formatdate(p, localtime=True)
135     'Sat, 05 Nov 1994 08:15:30 -0500'
136     >>> p - parse_date('1994-11-05T13:15:30Z')
137     0
138     """
139     m = _DATE_REGEXP.match(string)
140     if not m:
141         raise ValueError(string)
142     date,t,time,ms,zone = m.groups()
143     ret = None
144     if t:
145         date += 'T' + time
146     error = None
147     for fmt in ['%Y-%m-%dT%H:%M:%S',
148                 '%Y-%m-%dT%H:%M',
149                 '%Y-%m-%d',
150                 '%Y-%m',
151                 '%Y',
152                 ]:
153         try:
154             ret = _time.strptime(date, fmt)
155         except ValueError as e:
156             error = e
157         else:
158             break
159     if ret is None:
160         raise error
161     ret = list(ret)
162     ret[-1] = 0  # don't use daylight savings time
163     ret = _calendar.timegm(ret)
164     if ms:
165         ret += float(ms)
166     if zone and zone != 'Z':
167         sign = int(zone[1] + '1')
168         hour,minute = map(int, zone.split(':', 1))
169         offset = sign*(3600*hour + 60*minute)
170         ret -= offset
171     return ret
172
173 def load_assignment(name, data):
174     r"""Load an assignment from a ``dict``
175
176     >>> from email.utils import formatdate
177     >>> a = load_assignment(
178     ...     name='Attendance 1',
179     ...     data={'points': '1',
180     ...           'weight': '0.1/2',
181     ...           'due': '2011-10-04T00:00-04:00',
182     ...           })
183     >>> print('{0.name} (points: {0.points}, weight: {0.weight}, due: {0.due})'.format(a))
184     Attendance 1 (points: 1, weight: 0.05, due: 1317700800)
185     >>> print(formatdate(a.due, localtime=True))
186     Tue, 04 Oct 2011 00:00:00 -0400
187     """
188     points = int(data['points'])
189     wterms = data['weight'].split('/')
190     if len(wterms) == 1:
191         weight = float(wterms[0])
192     else:
193         assert len(wterms) == 2, wterms
194         weight = float(wterms[0])/float(wterms[1])
195     due = parse_date(data['due'])
196     return _Assignment(name=name, points=points, weight=weight, due=due)
197
198 def load_person(name, data={}):
199     r"""Load a person from a ``dict``
200
201     >>> from io import StringIO
202     >>> stream = StringIO('''#comment line
203     ... Tom Bombadil <tbomb@oldforest.net>  # post address comment
204     ... Tom Bombadil <yellow.boots@oldforest.net>
205     ... Goldberry <gb@oldforest.net>
206     ... ''')
207
208     >>> p = load_person(
209     ...     name='Gandalf',
210     ...     data={'nickname': 'G-Man',
211     ...           'emails': 'g@grey.edu, g@greyhavens.net',
212     ...           'pgp-key': '0x0123456789ABCDEF',
213     ...           })
214     >>> print('{0.name}: {0.emails} | {0.pgp_key}'.format(p))
215     Gandalf: ['g@grey.edu', 'g@greyhavens.net'] | 0x0123456789ABCDEF
216     >>> p = load_person(name='Gandalf')
217     >>> print('{0.name}: {0.emails} | {0.pgp_key}'.format(p))
218     Gandalf: None | None
219     """
220     kwargs = {}
221     emails = [x.strip() for x in data.get('emails', '').split(',')]
222     emails = list(filter(bool, emails))  # remove blank emails
223     if emails:
224         kwargs['emails'] = emails
225     nickname = data.get('nickname', None)
226     if nickname:
227         kwargs['aliases'] = [nickname]
228     pgp_key = data.get('pgp-key', None)
229     if pgp_key:
230         kwargs['pgp_key'] = pgp_key
231     return _Person(name=name, **kwargs)
232
233 def load_grades(basedir, assignments, people):
234     for assignment in assignments:
235         for person in people:
236             _LOG.debug('loading {} grade for {}'.format(assignment, person))
237             path = assignment_path(basedir, assignment, person)
238             gpath = _os_path.join(path, 'grade')
239             try:
240                 g = _load_grade(_io.open(gpath, 'r', encoding=_ENCODING),
241                                 assignment, person)
242             except IOError:
243                 continue
244             #g.late = _os.stat(gpath).st_mtime > assignment.due
245             g.late = _os_path.exists(_os_path.join(path, 'late'))
246             npath = _os_path.join(path, 'notified')
247             if _os_path.exists(npath):
248                 g.notified = newer(npath, gpath)
249             else:
250                 g.notified = False
251             yield g
252
253 def _load_grade(stream, assignment, person):
254     try:
255         points = float(stream.readline())
256     except ValueError:
257         _sys.stderr.write('failure reading {}, {}\n'.format(
258                 assignment.name, person.name))
259         raise
260     comment = stream.read().strip() or None
261     return _Grade(
262         student=person, assignment=assignment, points=points, comment=comment)
263
264 def assignment_path(basedir, assignment, person):
265     return _os_path.join(basedir,
266                   _filesystem_name(person.name),
267                   _filesystem_name(assignment.name))
268
269 def _filesystem_name(name):
270     for a,b in [(' ', '_'), ('.', ''), ("'", ''), ('"', '')]:
271         name = name.replace(a, b)
272     return name
273
274 def set_notified(basedir, grade):
275     """Mark `grade.student` as notified about `grade`
276     """
277     path = assignment_path(
278         basedir=basedir, assignment=grade.assignment, person=grade.student)
279     npath = _os_path.join(path, 'notified')
280     _touch(npath)
281
282 def set_late(basedir, assignment, person):
283     path = assignment_path(
284         basedir=basedir, assignment=assignment, person=person)
285     Lpath = _os_path.join(path, 'late')
286     _touch(Lpath)
287
288 def _touch(path):
289     """Touch a file (`path` is created if it doesn't already exist)
290
291     Also updates the access and modification times to the current
292     time.
293
294     >>> from os import listdir, rmdir, unlink
295     >>> from os.path import join
296     >>> from tempfile import mkdtemp
297     >>> d = mkdtemp(prefix='pygrader')
298     >>> listdir(d)
299     []
300     >>> p = join(d, 'touched')
301     >>> _touch(p)
302     >>> listdir(d)
303     ['touched']
304     >>> _touch(p)
305     >>> unlink(p)
306     >>> rmdir(d)
307     """
308     with open(path, 'a') as f:
309         pass
310     _os.utime(path, None)
311
312 def initialize(basedir, course, dry_run=False, **kwargs):
313     """Stub out the directory tree based on the course configuration.
314     """
315     for person in course.people:
316         for assignment in course.assignments:
317             path = assignment_path(basedir, assignment, person)
318             if dry_run:  # we'll need to guess if mkdirs would work
319                 if not _os_path.exists(path):
320                     _LOG.debug('creating {}'.format(path))
321             else:
322                 try:
323                     _os.makedirs(path)
324                 except OSError:
325                     continue
326                 else:
327                     _LOG.debug('creating {}'.format(path))