chpwd: Factor out option parsing.
authorMark Wooding <mdw@distorted.org.uk>
Mon, 22 Dec 2014 20:32:58 +0000 (20:32 +0000)
committerMark Wooding <mdw@distorted.org.uk>
Tue, 7 Apr 2015 18:49:13 +0000 (19:49 +0100)
chpwd

diff --git a/chpwd b/chpwd
index b4fc8f5..52d3fa3 100755 (executable)
--- a/chpwd
+++ b/chpwd
@@ -84,6 +84,18 @@ for short, long, props in [
     'help': "impersonate USER, and default context to `userv'." })]:
   OPTPARSE.add_option(short, long, **props)
 
+def parse_options():
+  """
+  Parse the main command-line options, returning the positional arguments.
+  """
+  global OPTS
+  OPTS, args = OPTPARSE.parse_args()
+  ## It's tempting to load the configuration here.  Don't do that.  Some
+  ## contexts will want to check that the command line was handled properly
+  ## upstream before believing it for anything, such as executing arbitrary
+  ## Python code.
+  return args
+
 ###--------------------------------------------------------------------------
 ### CGI dispatch.
 
@@ -96,10 +108,9 @@ CGI.SPECIAL['%user'] = None
 ## issuing redirects in the early setup phase fails because we don't know
 ## the script name.  So package the setup here.
 def cgi_setup(ctx = 'cgi-noauth'):
-  global OPTS
   if OPTS: return
   OPTPARSE.context = ctx
-  OPTS, args = OPTPARSE.parse_args()
+  args = parse_options()
   if args: raise U.ExpectedError, (500, 'Unexpected arguments to CGI')
   CONF.loadconfig(OPTS.config)
   D.opendb()
@@ -217,7 +228,7 @@ if __name__ == '__main__':
     ## `USERV_USER' environment variable.
 
     with cli_errors():
-      OPTS, args = OPTPARSE.parse_args()
+      args = parse_options()
       if not args or args[0] != 'userv':
         raise U.ExpectedError, (500, 'missing userv token')
       CONF.loadconfig(OPTS.config)
@@ -233,8 +244,7 @@ if __name__ == '__main__':
 
     def ssh_setup():
       """Extract and parse the client's request from where SSH left it."""
-      global OPTS
-      OPTS, args = OPTPARSE.parse_args()
+      args = parse_options()
       CONF.loadconfig(OPTS.config)
       cmd = SL.split(ENV['SSH_ORIGINAL_COMMAND'])
       if args: raise U.ExpectedError, (500, 'Unexpected arguments via SSH')
@@ -279,7 +289,7 @@ if __name__ == '__main__':
     ## as we are.
 
     with cli_errors():
-      OPTS, args = OPTPARSE.parse_args()
+      args = parse_options()
       CONF.loadconfig(OPTS.config)
       CGI.SSLP = OPTS.sslp
       ctx = OPTS.context