a1ad271b67e6003aa1cac0021e53f296429e39e8
[pygrader.git] / bin / pg.py
1 #!/usr/bin/env python3
2 #
3 # Copyright (C) 2012 W. Trevor King <wking@tremily.us>
4 #
5 # This file is part of pygrader.
6 #
7 # pygrader is free software: you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation, either version 3 of the License, or (at your option) any later
10 # version.
11 #
12 # pygrader is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along with
17 # pygrader.  If not, see <http://www.gnu.org/licenses/>.
18
19 """Manage grades from the command line
20 """
21
22 import configparser as _configparser
23 from email.mime.text import MIMEText as _MIMEText
24 import email.utils as _email_utils
25 import inspect as _inspect
26 import logging as _logging
27 import logging.handlers as _logging_handlers
28 import os.path as _os_path
29 import sys as _sys
30
31 import pgp_mime as _pgp_mime
32
33 import pygrader as _pygrader
34 from pygrader import __version__
35 from pygrader import LOG as _LOG
36 from pygrader import color as _color
37 from pygrader.email import test_smtp as _test_smtp
38 from pygrader.email import Responder as _Responder
39 from pygrader.mailpipe import mailpipe as _mailpipe
40 from pygrader.storage import initialize as _initialize
41 from pygrader.storage import load_course as _load_course
42 from pygrader.tabulate import tabulate as _tabulate
43 from pygrader.template import assignment_email as _assignment_email
44 from pygrader.template import course_email as _course_email
45 from pygrader.template import student_email as _student_email
46 from pygrader.todo import print_todo as _todo
47
48
49 if __name__ == '__main__':
50     from argparse import ArgumentParser as _ArgumentParser
51
52     parser = _ArgumentParser(
53         description=__doc__, version=__version__)
54     parser.add_argument(
55         '-d', '--base-dir', dest='basedir', default='.',
56         help='Base directory containing grade data')
57     parser.add_argument(
58         '-e', '--encoding', dest='encoding', default='utf-8',
59         help=('Override the default file encoding selection '
60               '(useful when running from procmail)'))
61     parser.add_argument(
62         '-c', '--color', default=False, action='store_const', const=True,
63         help='Color printed output with ANSI escape sequences')
64     parser.add_argument(
65         '-V', '--verbose', default=0, action='count',
66         help='Increase verbosity')
67     parser.add_argument(
68         '-s', '--syslog', default=False, action='store_const', const=True,
69         help='Log to syslog (rather than stderr)')
70     subparsers = parser.add_subparsers(title='commands')
71
72     smtp_parser = subparsers.add_parser(
73         'smtp', help=_test_smtp.__doc__.splitlines()[0])
74     smtp_parser.set_defaults(func=_test_smtp)
75     smtp_parser.add_argument(
76         '-a', '--author',
77         help='Your address (email author)')
78     smtp_parser.add_argument(
79         '-t', '--target', dest='targets', action='append',
80         help='Address for the email recipient')
81
82     initialize_parser = subparsers.add_parser(
83         'initialize', help=_initialize.__doc__.splitlines()[0])
84     initialize_parser.set_defaults(func=_initialize)
85     initialize_parser.add_argument(
86         '-D', '--dry-run', default=False, action='store_const', const=True,
87         help="Don't actually send emails, create files, etc.")
88
89     tabulate_parser = subparsers.add_parser(
90         'tabulate', help=_tabulate.__doc__.splitlines()[0])
91     tabulate_parser.set_defaults(func=_tabulate)
92     tabulate_parser.add_argument(
93         '-s', '--statistics', default=False, action='store_const', const=True,
94         help='Calculate mean and standard deviation for each assignment')
95
96     email_parser = subparsers.add_parser(
97         'email', help='Send emails containing grade information')
98     email_parser.add_argument(
99         '-D', '--dry-run', default=False, action='store_const', const=True,
100         help="Don't actually send emails, create files, etc.")
101     email_parser.add_argument(
102         '-a', '--author',
103         help='Your name (email author), defaults to course robot')
104     email_parser.add_argument(
105         '--cc', action='append', help='People to carbon copy')
106     email_subparsers = email_parser.add_subparsers(title='type')
107     assignment_parser = email_subparsers.add_parser(
108         'assignment', help=_assignment_email.__doc__.splitlines()[0])
109     assignment_parser.set_defaults(func=_assignment_email)
110     assignment_parser.add_argument(
111         'assignment', help='Name of the target assignment')
112     student_parser = email_subparsers.add_parser(
113         'student', help=_student_email.__doc__.splitlines()[0])
114     student_parser.set_defaults(func=_student_email)
115     student_parser.add_argument(
116         '-o', '--old', default=False, action='store_const', const=True,
117         help='Include already-notified information in emails')
118     student_parser.add_argument(
119         '-s', '--student', dest='student',
120         help='Explicitly select the student to notify (instead of everyone)')
121     course_parser = email_subparsers.add_parser(
122         'course', help=_course_email.__doc__.splitlines()[0])
123     course_parser.set_defaults(func=_course_email)
124     course_parser.add_argument(
125         '-t', '--target', dest='targets', action='append',
126         help='Name, alias, or group for the email recipient(s)')
127
128     mailpipe_parser = subparsers.add_parser(
129         'mailpipe', help=_mailpipe.__doc__.splitlines()[0])
130     mailpipe_parser.set_defaults(func=_mailpipe)
131     mailpipe_parser.add_argument(
132         '-D', '--dry-run', default=False, action='store_const', const=True,
133         help="Don't actually send emails, create files, etc.")
134     mailpipe_parser.add_argument(
135         '-m', '--mailbox', choices=['maildir', 'mbox'],
136         help=('Instead of piping a message in via stdout, you can also read '
137               'directly from a mailbox.  This option specifies the format of '
138               'your target mailbox.'))
139     mailpipe_parser.add_argument(
140         '-i', '--input', dest='input_', metavar='INPUT',
141         help='Path to the mailbox containing messages to be processed')
142     mailpipe_parser.add_argument(
143         '-o', '--output',
144         help=('Path to the mailbox that will recieve successfully processed '
145               'messages.  If not given, successfully processed messages will '
146               'be left in the input mailbox'))
147     mailpipe_parser.add_argument(
148         '-l', '--max-late', default=0, type=float,
149         help=('Grace period in seconds before an incoming assignment is '
150               'actually marked as late'))
151     mailpipe_parser.add_argument(
152         '-r', '--respond', default=False, action='store_const', const=True,
153         help=('Send automatic response emails to acknowledge incoming '
154               'messages.'))
155     mailpipe_parser.add_argument(
156         '-t', '--trust-email-infrastructure',
157         default=False, action='store_const', const=True,
158         help=('Send automatic response emails even if the target has not '
159               'registered a PGP key.'))
160
161     todo_parser = subparsers.add_parser(
162         'todo', help=_todo.__doc__.splitlines()[0])
163     todo_parser.set_defaults(func=_todo)
164     todo_parser.add_argument(
165         'source', help='Name of source file/directory')
166     todo_parser.add_argument(
167         'target', help='Name of target file/directory')
168
169
170 #    p.add_option('-t', '--template', default=None)
171
172     args = parser.parse_args()
173
174     if args.verbose:
175         _LOG.setLevel(max(_logging.DEBUG, _LOG.level - 10*args.verbose))
176         _pgp_mime.LOG.setLevel(_LOG.level)
177     if args.syslog:
178         syslog = _logging_handlers.SysLogHandler(address="/dev/log")
179         syslog.setFormatter(_logging.Formatter('%(name)s: %(message)s'))
180         for handler in list(_LOG.handlers):
181             _LOG.removeHandler(handler)
182         _LOG.addHandler(syslog)
183         for handler in list(_pgp_mime.LOG.handlers):
184             _pgp_mime.LOG.removeHandler(handler)
185         _pgp_mime.LOG.addHandler(syslog)
186     _color.USE_COLOR = args.color
187
188     _pygrader.ENCODING = args.encoding
189
190     config = _configparser.ConfigParser()
191     config.read([
192             _os_path.expanduser(_os_path.join('~', '.config', 'smtplib.conf')),
193             ], encoding=_pygrader.ENCODING)
194
195     func_args = _inspect.getargspec(args.func).args
196     kwargs = {}
197
198     if 'basedir' in func_args:
199         kwargs['basedir'] = args.basedir
200
201     if 'course' in func_args:
202         course = _load_course(basedir=args.basedir)
203         active_groups = course.active_groups()
204         kwargs['course'] = course
205         if hasattr(args, 'assignment'):
206             kwargs['assignment'] = course.assignment(name=args.assignment)
207         if hasattr(args, 'cc') and args.cc:
208             kwargs['cc'] = [course.person(name=cc) for cc in args.cc]
209         for attr in ['author', 'student']:
210             if hasattr(args, attr):
211                 name = getattr(args, attr)
212                 if name is None and attr == 'author':
213                     kwargs[attr] = course.robot
214                 else:
215                     kwargs[attr] = course.person(name=name)
216         for attr in ['targets']:
217             if hasattr(args, attr):
218                 people = getattr(args, attr)
219                 if people is None:
220                     people = ['professors']  # for the course email
221                 kwargs[attr] = []
222                 for person in people:
223                     if person in active_groups:
224                         kwargs[attr].extend(course.find_people(group=person))
225                     else:
226                         kwargs[attr].extend(course.find_people(name=person))
227         for attr in ['dry_run', 'mailbox', 'output', 'input_', 'max_late',
228                      'old', 'statistics', 'trust_email_infrastructure']:
229             if hasattr(args, attr):
230                 kwargs[attr] = getattr(args, attr)
231     elif args.func == _test_smtp:
232         for attr in ['author', 'targets']:
233             if hasattr(args, attr):
234                 kwargs[attr] = getattr(args, attr)
235     elif args.func == _todo:
236         for attr in ['source', 'target']:
237             if hasattr(args, attr):
238                 kwargs[attr] = getattr(args, attr)
239
240     if args.func == _mailpipe:
241         kwargs['continue_after_invalid_message'] = True
242
243     if 'use_color' in func_args:
244         kwargs['use_color'] = args.color
245
246     if ('smtp' in func_args and
247         not kwargs.get('dry_run', False) and
248         'smtp' in config.sections()):
249         params = _pgp_mime.get_smtp_params(config)
250         kwargs['smtp'] = _pgp_mime.get_smtp(*params)
251         del params
252
253     if hasattr(args, 'respond') and getattr(args, 'respond'):
254         kwargs['respond'] = _Responder(
255             smtp=kwargs.get('smtp', None),
256             dry_run=kwargs.get('dry_run', False))
257
258     _LOG.debug('execute {} with {}'.format(args.func, kwargs))
259     try:
260         ret = args.func(**kwargs)
261     finally:
262         smtp = kwargs.get('smtp', None)
263         if smtp:
264             _LOG.info('disconnect from SMTP server')
265             smtp.quit()
266     if ret is None:
267         ret = 0
268     _sys.exit(ret)