3 # Copyright (C) 2012 W. Trevor King <wking@tremily.us>
5 # This file is part of pygrader.
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
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.
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/>.
19 """Manage grades from the command line
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
31 import pgp_mime as _pgp_mime
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
48 if __name__ == '__main__':
49 from argparse import ArgumentParser as _ArgumentParser
51 parser = _ArgumentParser(
52 description=__doc__, version=__version__)
54 '-d', '--base-dir', dest='basedir', default='.',
55 help='Base directory containing grade data')
57 '-c', '--color', default=False, action='store_const', const=True,
58 help='Color printed output with ANSI escape sequences')
60 '-V', '--verbose', default=0, action='count',
61 help='Increase verbosity')
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')
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(
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')
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.")
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')
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(
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)')
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(
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 '
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.'))
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')
165 # p.add_option('-t', '--template', default=None)
167 args = parser.parse_args()
170 _LOG.setLevel(max(_logging.DEBUG, _LOG.level - 10*args.verbose))
171 _pgp_mime.LOG.setLevel(_LOG.level)
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
183 config = _configparser.ConfigParser()
185 _os_path.expanduser(_os_path.join('~', '.config', 'smtplib.conf')),
188 func_args = _inspect.getargspec(args.func).args
191 if 'basedir' in func_args:
192 kwargs['basedir'] = args.basedir
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
208 kwargs[attr] = course.person(name=name)
209 for attr in ['targets']:
210 if hasattr(args, attr):
211 people = getattr(args, attr)
213 people = ['professors'] # for the course email
215 for person in people:
216 if person in active_groups:
217 kwargs[attr].extend(course.find_people(group=person))
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)
233 if args.func == _mailpipe:
234 kwargs['continue_after_invalid_message'] = True
236 if 'use_color' in func_args:
237 kwargs['use_color'] = args.color
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)
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))
251 _LOG.debug('execute {} with {}'.format(args.func, kwargs))
253 ret = args.func(**kwargs)
255 smtp = kwargs.get('smtp', None)
257 _LOG.info('disconnect from SMTP server')