SF.net SVN: tmda: [2101] trunk/tmda/bin

[email protected] Thu, 12 Oct 2006 21:32:21 -0700
Newsgroups gmane.mail.spam.tmda.cvs
Message-ID <[email protected]>
Revision: 2101
          http://svn.sourceforge.net/tmda/?rev=2101&view=rev
Author:   jasonrm
Date:     2006-10-12 21:32:15 -0700 (Thu, 12 Oct 2006)

Log Message:
-----------
Migrate from getopt to optparse.  Still need to find a good
way to include explanation of "messages" and also "Examples"
in the help output, so for now I've left them out.

Modified Paths:
--------------
    trunk/tmda/bin/ChangeLog
    trunk/tmda/bin/tmda-pending

Modified: trunk/tmda/bin/ChangeLog
===================================================================
--- trunk/tmda/bin/ChangeLog	2006-10-13 02:35:27 UTC (rev 2100)
+++ trunk/tmda/bin/ChangeLog	2006-10-13 04:32:15 UTC (rev 2101)
@@ -1,9 +1,10 @@
 2006-10-12  Jason R. Mastaler  <[email protected]>
 
-	* tmda-address: Migrate from getopt to optparse.
+	* tmda-pending: Migrate from getopt to optparse.
 
-	Add new option '-t/--timeout'.  '-d/--dated' no longer accepts an
-	optional argument.
+	* tmda-address: Migrate from getopt to optparse.  Also add new
+	option '-t/--timeout'.  '-d/--dated' no longer accepts an optional
+	argument.
 
 2006-10-11  Jason R. Mastaler  <[email protected]>
 

Modified: trunk/tmda/bin/tmda-pending
===================================================================
--- trunk/tmda/bin/tmda-pending	2006-10-13 02:35:27 UTC (rev 2100)
+++ trunk/tmda/bin/tmda-pending	2006-10-13 04:32:15 UTC (rev 2101)
@@ -19,290 +19,196 @@
 # along with TMDA; if not, write to the Free Software Foundation, Inc.,
 # 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
-"""Pending queue manipulation tool.
 
-Usage:  %(program)s [OPTIONS] [messages ... | - ]
+from optparse import OptionGroup, OptionParser
 
-Where:
-    -c <file>
-    --config-file <file>
-       Specify a different configuration file other than ~/.tmda/config.
+import os
+import sys
 
-    -i
-    --interactive
-       Display a summary of each pending message and prompt for
-       disposal (pass, show, release, delete, quit).  Implies
-       --verbose.  (default)
+try:
+    import paths
+except ImportError:
+    # Prepend /usr/lib/python2.x/site-packages/TMDA/pythonlib
+    sitedir = os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3],
+                           'site-packages', 'TMDA', 'pythonlib')
+    sys.path.insert(0, sitedir)
 
-    -p
-    --pretend
-       Don't actually operate on messages, just show what would have happened.
-       Implies --verbose.
+import email
 
-    -b
-    --batch
-       Operate non-interactively.  Use with caution.
-       
-    -r
-    --release
-       Release messages.
+from TMDA import Version
 
-    -d
-    --delete
-       Delete messages.
 
-    -B
-    --blacklist
-       Append the sender of the message to the PENDING_BLACKLIST_APPEND file.
+# option parsing
 
-    -W
-    --whitelist
-       Append the sender of the message to the PENDING_WHITELIST_APPEND file.
+opt_usage = "%prog [options] [messages ... | - ]"
 
-    -s
-    --summary
-       Print a summary of pending messages along with a release address link.
-       Implies --verbose.
+opt_desc = "A TMDA pending queue manipulation tool."
 
-    -T
-    --terse-summary
-       Print a terse (one-line per message) summary of pending messages.
-       Customize display with TERSE_SUMMARY_HEADERS. Implies --verbose.
-       
-    -S
-    --show
-       Display the full contents of the given message with $PAGER (usually
-       the `more', or `less' program).
-       
-    -C
-    --cache
-       Operate only on messages which aren't stored in .msgcache (i.e,
-       haven't yet been seen).  After operation, store the message in
-       .msgcache.  Useful primarily in conjunction with the --summary
-       option.
-       
-    -A
-    --ascending
-       Operate on messages in ascending order (default).
+parser = OptionParser(version=Version.TMDA, usage=opt_usage, description=opt_desc)
 
-    -D
-    --descending
-       Operate on messages in descending order.
-      
-    -R <user@host>
-    --recipient <user@host>
-       Override the address used to create the magic release address.
-       Normally, this is determined by parsing the `X-TMDA-Recipient'
-       header which every pending message should contain.
+parser.add_option("-V", 
+		  action="store_true", default=False, dest="full_version",
+		  help="show full TMDA version information and exit.")
 
-    -Y <interval>
-    --younger <interval>
-       Operate only on messages younger than the time interval given in
-       seconds (s), minutes (m), hours (h), days (d), weeks (w), months
-       (M), or years (Y).
+# option groups
+gengroup = OptionGroup(parser, "General")
+actngroup = OptionGroup(parser, "Actions")
+msggroup = OptionGroup(parser, "Messages")
 
-    -O <interval>
-    --older <interval>
-       Operate only on messages older than the time interval given in
-       seconds (s), minutes (m), hours (h), days (d), weeks (w), months
-       (M), or years (Y).
+# general
+gengroup.add_option("-c", "--config-file",
+                    metavar="FILE", dest="config_file",
+                    help= \
+"""Specify a different configuration file other than ~/.tmda/config""")
 
-    -v
-    --verbose
-       Display output (default).
+gengroup.add_option("-v", "--verbose",
+                    action="store_true", default=True, dest="verbose",
+                    help="Display output (default).")
 
-    -q
-    --quiet
-       Suppress output.  Not compatible with --interactive.
+gengroup.add_option("-q", "--quiet",
+                    action="store_false", dest="verbose",
+                    help="Suppress output.  Not compatible with '--interactive.'")
 
-    -V
-    --version
-       Print TMDA version information and exit.
- 
-    -h
-    --help
-       Print this help message and exit.
+gengroup.add_option("-p", "--pretend",
+                    action="store_true", dest="pretend",
+                    help= \
+"""Don't actually operate on messages, just show what would have
+happened.  Implies '--verbose'.""")
 
-    messages | -
-       If one or more messages are provided, operate just on them. 
-       If `-' is specified, operate on a list of messages provided by
-       standard input. Otherwise, operate on all messages in the pending queue.
-       
-    Examples:
+gengroup.add_option("-i", "--interactive",
+                    action="store_true", default=True, dest="interactive",
+                    help= \
+"""Display a summary of each pending message and prompt for disposal
+(pass, show, release, delete, quit).  Implies '--verbose'. (default)""")
 
-    (interactively operate on all pending messages)
-    %(program)s 
+gengroup.add_option("-b", "--batch",
+                    action="store_false", dest="interactive",
+                    help= \
+"""Operate non-interactively in batch mode. Use with caution.""")
 
-    (get a summary listing of all pending messages)
-    %(program)s -T -b
+gengroup.add_option("-C", "--cache",
+                    action="store_true", dest="cache",
+                    help= \
+"""Operate only on messages which aren't stored in
+ /.tmda/.pendingcache (i.e, haven't yet been read).  After operation,
+ store the message in the cache file.  Useful primarily in conjunction
+ with the '--summary' option.""")
 
-    (interactively operate on just these messages)
-    %(program)s 1012182077.5803 1012939546.7870
+# actions
 
-    (immediately release these messages from the pending queue)
-    %(program)s -b -r 1012182077.5803 1012939546.7870
+actngroup.add_option("-r", "--release",
+                     action="store_const", const="release", dest="dispose",
+                     help="Release messages.")
 
-    (immediately release any messages with `foobar' in them)
-    %(program)s -b -T | grep foobar | awk '{print $1}' | %(program)s -b -r -
+actngroup.add_option("-R", "--recipient",
+                     metavar="ADDRESS", dest="command_recipient",
+                     help= \
+"""Override the email address used to create the magic release address
+by specifying ADDRESS.  Normally, this is determined by parsing the
+`X-TMDA-Recipient' header which every pending message contains.""")
 
-    (immediately delete all messages from the pending queue)
-    %(program)s -b -d
+actngroup.add_option("-d", "--delete",
+                     action="store_const", const="delete", dest="dispose",
+                     help="Delete messages.")
 
-    (silently and immediately delete all messages older than 30 days)
-    %(program)s -q -b -d -O 30d
-    
-    (mail a summary report of all new pending messages)
-    %(program)s -C -b -s | mail -s 'TMDA pending summary' jason
-"""
+actngroup.add_option("-B", "--blacklist",
+                     action="store_const", const="blacklist", dest="dispose",
+                     help= \
+"""Append the sender of the message to the PENDING_BLACKLIST_APPEND file.""")
 
-import getopt
-import os
-import sys
+actngroup.add_option("-W", "--whitelist",
+                     action="store_const", const="whitelist", dest="dispose",
+                     help= \
+"""Append the sender of the message to the PENDING_WHITELIST_APPEND file.""")
 
-try:
-    import paths
-except ImportError:
-    # Prepend /usr/lib/python2.x/site-packages/TMDA/pythonlib
-    sitedir = os.path.join(sys.prefix, 'lib', 'python'+sys.version[:3],
-                           'site-packages', 'TMDA', 'pythonlib')
-    sys.path.insert(0, sitedir)
+actngroup.add_option("-S", "--show",
+                     action="store_const", const="show", dest="dispose",
+                     help= \
+"""Display the full contents of the given message with $PAGER (usually
+the `more', or `less' program).""")
 
-import email
+actngroup.add_option("-s", "--summary",
+                     action="store_true", dest="summary",
+                     help= \
+"""Print a summary of pending messages along with a release address
+link. Implies '--verbose'.""")
 
-from TMDA import Version
+actngroup.add_option("-T", "--terse-summary",
+                     action="store_true", dest="terse",
+                     help= \
+"""Print a terse (one-line per message) summary of pending messages.
+Customize the display with TERSE_SUMMARY_HEADERS. Implies '--verbose'.""")
 
+# messages
 
-program = sys.argv[0]
-# Defaults
-cache = None
-command_recipient = None
-descending = None
-dispose = None
-interactive = 1
-older = None
-pretend = None
-summary = None
-terse = None
-threshold = None
-verbose = 1
-younger = None
+msggroup.add_option("-A", "--ascending",
+                    action="store_false", dest="descending",
+                    help="Operate on messages in ascending order (default).")
 
+msggroup.add_option("-D", "--descending",
+                    action="store_true", dest="descending",
+                    help="Operate on messages in descending order.")
 
-def usage(code, msg=''):
-    print __doc__ % globals()
-    if msg:
-        print msg
-    sys.exit(code)
+msggroup.add_option("-Y", "--younger",
+                    metavar="INTERVAL", dest="younger",
+                    help= \
+"""Operate only on messages younger than the time INTERVAL given in
+seconds (s), minutes (m), hours (h), days (d), weeks (w), months (M),
+or years (Y).""")
 
-try:
-    opts, args = getopt.getopt(sys.argv[1:],
-                               'c:ipbrdBWsTSCADR:Y:O:vqVh', ['config-file=',
-                                                             'interactive',
-                                                             'pretend',
-                                                             'batch',
-                                                             'release',
-                                                             'delete',
-                                                             'blacklist',
-                                                             'whitelist',
-                                                             'summary',
-                                                             'terse-summary',
-                                                             'show',
-                                                             'cache',
-                                                             'ascending',
-                                                             'descending',
-                                                             'recipient=',
-                                                             'younger=',
-                                                             'older=',
-                                                             'verbose',
-                                                             'quiet',
-                                                             'version',
-                                                             'help'])
-except getopt.error, msg:
-    usage(1, msg)
+msggroup.add_option("-O", "--older",
+                    metavar="INTERVAL", dest="older",
+                    help= \
+"""Operate only on messages older than the time INTERVAL given in
+seconds (s), minutes (m), hours (h), days (d), weeks (w), months (M),
+or years (Y).""")
 
-for opt, arg in opts:
-    if opt in ('-h', '--help'):
-        usage(0)
-    if opt == '-V':
-        print Version.ALL
-        sys.exit()
-    if opt == '--version':
-        print Version.TMDA
-        sys.exit()
-    elif opt in ('-c', '--config-file'):
-        os.environ['TMDARC'] = arg
-    elif opt in ('-i', '--interactive'):
-        interactive = verbose = 1
-    elif opt in ('-p', '--pretend'):
-        pretend = verbose = 1
-    elif opt in ('-b', '--batch'):
-        interactive = 0
-    elif opt in ('-r', '--release'):
-        dispose = 'release'
-    elif opt in ('-d', '--delete'):
-        dispose = 'delete'
-    elif opt in ('-B', '--blacklist'):
-        dispose = 'blacklist'
-    elif opt in ('-W', '--whitelist'):
-        dispose = 'whitelist'
-    elif opt in ('-s', '--summary'):
-        summary = 1
-    elif opt in ('-T', '--terse-summary'):
-        terse = 1
-    elif opt in ('-S', '--show'):
-        dispose = 'show'
-    elif opt in ('-C', '--cache'):
-        cache = 1
-    elif opt in ('-A', '--ascending'):
-        descending = 0
-    elif opt in ('-D', '--descending'):
-        descending = 1
-    elif opt in ('-R', '--recipient'):
-        command_recipient = arg
-    elif opt in ('-Y', '--younger'):
-        younger = 1
-        threshold = arg
-    elif opt in ('-O', '--older'):
-        older = 1
-        threshold = arg
-    elif opt in ('-q', '--quiet'):
-        verbose = 0
-    elif opt in ('-v', '--verbose'):
-        verbose = 1
+for g in (gengroup, actngroup, msggroup):
+    parser.add_option_group(g)
 
+(opts, args) = parser.parse_args()
 
+if opts.full_version:
+    print Version.ALL
+    sys.exit()
+
+if opts.config_file:
+     os.environ['TMDARC'] = opts.config_file
+
+if opts.pretend or opts.interactive:
+    opts.verbose = True
+
+if opts.younger:
+    threshold = opts.younger
+elif opts.older:
+    threshold = opts.older
+else:
+    threshold = None
+
+
 from TMDA import Pending
 from TMDA import Errors
 
-def cprint(verbose=1, *strings):
-    """Conditionally print one or more strings."""
-    if verbose:
-        for s in strings:
-            print s,
-        print
-    else:
-        return
 
 def main():
-
-    if interactive:
+    if opts.interactive:
         QueueObject = Pending.InteractiveQueue
     else:
         QueueObject = Pending.Queue
     try:
         q = QueueObject(
             msgs = args,
-            cache = cache,
-            command_recipient = command_recipient,
-            descending = descending,
-            dispose = dispose,
-            older = older,
-            summary = summary,
-            terse = terse,
+            cache = opts.cache,
+            command_recipient = opts.command_recipient,
+            descending = opts.descending,
+            dispose = opts.dispose,
+            older = opts.older,
+            summary = opts.summary,
+            terse = opts.terse,
             threshold = threshold,
-            verbose = verbose,
-            younger = younger,
-            pretend = pretend
+            verbose = opts.verbose,
+            younger = opts.younger,
+            pretend = opts.pretend
             ).initQueue()
         q.mainLoop()
     except Errors.QueueError, obj:


This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.