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