py.py: add -s/--syslog to redirect logging to syslog (/dev/log).
[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 from pygrader import __version__
34 from pygrader import LOG as _LOG
35 from pygrader import color as _color
36 from pygrader.email import test_smtp as _test_smtp
37 from pygrader.email import Responder as _Responder
38 from pygrader.mailpipe import mailpipe as _mailpipe
39 from pygrader.storage import initialize as _initialize
40 from pygrader.storage import load_course as _load_course
41 from pygrader.tabulate import tabulate as _tabulate
42 from pygrader.template import assignment_email as _assignment_email
43 from pygrader.template import course_email as _course_email
44 from pygrader.template import student_email as _student_email
45 from pygrader.todo import print_todo as _todo
46
47
48 if __name__ == '__main__':
49     from argparse import ArgumentParser as _ArgumentParser
50
51     parser = _ArgumentParser(
52         description=__doc__, version=__version__)
53     parser.add_argument(
54         '-d', '--base-dir', dest='basedir', default='.',
55         help='Base directory containing grade data')
56     parser.add_argument(
57         '-c', '--color', default=False, action='store_const', const=True,
58         help='Color printed output with ANSI escape sequences')
59     parser.add_argument(
60         '-V', '--verbose', default=0, action='count',
61         help='Increase verbosity')
62     parser.add_argument(
63         '-s', '--syslog', default=False, action='store_const', const=True,
64         help='Log to syslog (rather than stderr)')
65     subparsers = parser.add_subparsers(title='commands')
66
67     smtp_parser = subparsers.add_parser(
68         'smtp', help=_test_smtp.__doc__.splitlines()[0])
69     smtp_parser.set_defaults(func=_test_smtp)
70     smtp_parser.add_argument(
71         '-a', '--author',
72         help='Your address (email author)')
73     smtp_parser.add_argument(
74         '-t', '--target', dest='targets', action='append',
75         help='Address for the email recipient')
76
77     initialize_parser = subparsers.add_parser(
78         'initialize', help=_initialize.__doc__.splitlines()[0])
79     initialize_parser.set_defaults(func=_initialize)
80     initialize_parser.add_argument(
81         '-D', '--dry-run', default=False, action='store_const', const=True,
82         help="Don't actually send emails, create files, etc.")
83
84     tabulate_parser = subparsers.add_parser(
85         'tabulate', help=_tabulate.__doc__.splitlines()[0])
86     tabulate_parser.set_defaults(func=_tabulate)
87     tabulate_parser.add_argument(
88         '-s', '--statistics', default=False, action='store_const', const=True,
89         help='Calculate mean and standard deviation for each assignment')
90
91     email_parser = subparsers.add_parser(
92         'email', help='Send emails containing grade information')
93     email_parser.add_argument(
94         '-D', '--dry-run', default=False, action='store_const', const=True,
95         help="Don't actually send emails, create files, etc.")
96     email_parser.add_argument(
97         '-a', '--author',
98         help='Your name (email author), defaults to course robot')
99     email_parser.add_argument(
100         '--cc', action='append', help='People to carbon copy')
101     email_subparsers = email_parser.add_subparsers(title='type')
102     assignment_parser = email_subparsers.add_parser(
103         'assignment', help=_assignment_email.__doc__.splitlines()[0])
104     assignment_parser.set_defaults(func=_assignment_email)
105     assignment_parser.add_argument(
106         'assignment', help='Name of the target assignment')
107     student_parser = email_subparsers.add_parser(
108         'student', help=_student_email.__doc__.splitlines()[0])
109     student_parser.set_defaults(func=_student_email)
110     student_parser.add_argument(
111         '-o', '--old', default=False, action='store_const', const=True,
112         help='Include already-notified information in emails')
113     student_parser.add_argument(
114         '-s', '--student', dest='student',
115         help='Explicitly select the student to notify (instead of everyone)')
116     course_parser = email_subparsers.add_parser(
117         'course', help=_course_email.__doc__.splitlines()[0])
118     course_parser.set_defaults(func=_course_email)
119     course_parser.add_argument(
120         '-t', '--target', dest='targets', action='append',
121         help='Name, alias, or group for the email recipient(s)')
122
123     mailpipe_parser = subparsers.add_parser(
124         'mailpipe', help=_mailpipe.__doc__.splitlines()[0])
125     mailpipe_parser.set_defaults(func=_mailpipe)
126     mailpipe_parser.add_argument(
127         '-D', '--dry-run', default=False, action='store_const', const=True,
128         help="Don't actually send emails, create files, etc.")
129     mailpipe_parser.add_argument(
130         '-m', '--mailbox', choices=['maildir', 'mbox'],
131         help=('Instead of piping a message in via stdout, you can also read '
132               'directly from a mailbox.  This option specifies the format of '
133               'your target mailbox.'))
134     mailpipe_parser.add_argument(
135         '-i', '--input', dest='input_', metavar='INPUT',
136         help='Path to the mailbox containing messages to be processed')
137     mailpipe_parser.add_argument(
138         '-o', '--output',
139         help=('Path to the mailbox that will recieve successfully processed '
140               'messages.  If not given, successfully processed messages will '
141               'be left in the input mailbox'))
142     mailpipe_parser.add_argument(
143         '-l', '--max-late', default=0, type=float,
144         help=('Grace period in seconds before an incoming assignment is '
145               'actually marked as late'))
146     mailpipe_parser.add_argument(
147         '-r', '--respond', default=False, action='store_const', const=True,
148         help=('Send automatic response emails to acknowledge incoming '
149               'messages.'))
150     mailpipe_parser.add_argument(
151         '-t', '--trust-email-infrastructure',
152         default=False, action='store_const', const=True,
153         help=('Send automatic response emails even if the target has not '
154               'registered a PGP key.'))
155
156     todo_parser = subparsers.add_parser(
157         'todo', help=_todo.__doc__.splitlines()[0])
158     todo_parser.set_defaults(func=_todo)
159     todo_parser.add_argument(
160         'source', help='Name of source file/directory')
161     todo_parser.add_argument(
162         'target', help='Name of target file/directory')
163
164
165 #    p.add_option('-t', '--template', default=None)
166
167     args = parser.parse_args()
168
169     if args.verbose:
170         _LOG.setLevel(max(_logging.DEBUG, _LOG.level - 10*args.verbose))
171         _pgp_mime.LOG.setLevel(_LOG.level)
172     if args.syslog:
173         syslog = _logging_handlers.SysLogHandler(address="/dev/log")
174         syslog.setFormatter(_logging.Formatter('%(name)s: %(message)s'))
175         for handler in list(_LOG.handlers):
176             _LOG.removeHandler(handler)
177         _LOG.addHandler(syslog)
178         for handler in list(_pgp_mime.LOG.handlers):
179             _pgp_mime.LOG.removeHandler(handler)
180         _pgp_mime.LOG.addHandler(syslog)
181     _color.USE_COLOR = args.color
182
183     config = _configparser.ConfigParser()
184     config.read([
185             _os_path.expanduser(_os_path.join('~', '.config', 'smtplib.conf')),
186             ])
187
188     func_args = _inspect.getargspec(args.func).args
189     kwargs = {}
190
191     if 'basedir' in func_args:
192         kwargs['basedir'] = args.basedir
193
194     if 'course' in func_args:
195         course = _load_course(basedir=args.basedir)
196         active_groups = course.active_groups()
197         kwargs['course'] = course
198         if hasattr(args, 'assignment'):
199             kwargs['assignment'] = course.assignment(name=args.assignment)
200         if hasattr(args, 'cc') and args.cc:
201             kwargs['cc'] = [course.person(name=cc) for cc in args.cc]
202         for attr in ['author', 'student']:
203             if hasattr(args, attr):
204                 name = getattr(args, attr)
205                 if name is None and attr == 'author':
206                     kwargs[attr] = course.robot
207                 else:
208                     kwargs[attr] = course.person(name=name)
209         for attr in ['targets']:
210             if hasattr(args, attr):
211                 people = getattr(args, attr)
212                 if people is None:
213                     people = ['professors']  # for the course email
214                 kwargs[attr] = []
215                 for person in people:
216                     if person in active_groups:
217                         kwargs[attr].extend(course.find_people(group=person))
218                     else:
219                         kwargs[attr].extend(course.find_people(name=person))
220         for attr in ['dry_run', 'mailbox', 'output', 'input_', 'max_late',
221                      'old', 'statistics', 'trust_email_infrastructure']:
222             if hasattr(args, attr):
223                 kwargs[attr] = getattr(args, attr)
224     elif args.func == _test_smtp:
225         for attr in ['author', 'targets']:
226             if hasattr(args, attr):
227                 kwargs[attr] = getattr(args, attr)
228     elif args.func == _todo:
229         for attr in ['source', 'target']:
230             if hasattr(args, attr):
231                 kwargs[attr] = getattr(args, attr)
232
233     if args.func == _mailpipe:
234         kwargs['continue_after_invalid_message'] = True
235
236     if 'use_color' in func_args:
237         kwargs['use_color'] = args.color
238
239     if ('smtp' in func_args and
240         not kwargs.get('dry_run', False) and
241         'smtp' in config.sections()):
242         params = _pgp_mime.get_smtp_params(config)
243         kwargs['smtp'] = _pgp_mime.get_smtp(*params)
244         del params
245
246     if hasattr(args, 'respond') and getattr(args, 'respond'):
247         kwargs['respond'] = _Responder(
248             smtp=kwargs.get('smtp', None),
249             dry_run=kwargs.get('dry_run', False))
250
251     _LOG.debug('execute {} with {}'.format(args.func, kwargs))
252     try:
253         ret = args.func(**kwargs)
254     finally:
255         smtp = kwargs.get('smtp', None)
256         if smtp:
257             _LOG.info('disconnect from SMTP server')
258             smtp.quit()
259     if ret is None:
260         ret = 0
261     _sys.exit(ret)