Synopsis - Cross-Reference

File: /scripts/sxr-server
  1#!/usr/bin/env python
  2#
  3# Copyright (C) 2004 Stefan Seefeld
  4# All rights reserved.
  5# Licensed to the public under the terms of the GNU LGPL (>= 2),
  6# see the file COPYING for details.
  7#
  8
  9from Synopsis import config
 10from Synopsis.SXRServer import SXRServer
 11from BaseHTTPServer import HTTPServer
 12from CGIHTTPServer import CGIHTTPRequestHandler
 13import sys, os, os.path, getopt, socket, urllib, cgi
 14
 15class SXRConfig:
 16    """Mixin base class to hold config parameters."""
 17    
 18    cgi_url = ''
 19    src_url = ''
 20    document_root = '.'
 21    debug = False
 22    sxr_server = None
 23
 24class RequestHandler(CGIHTTPRequestHandler, SXRConfig):
 25    """This little demo server emulates apache's 'Alias' and 'ScriptAlias'
 26    options to serve source files and data generated from sxr.cgi"""
 27
 28
 29    def translate_path(self, path):
 30        """Translate URL into local path."""
 31
 32        if path.endswith('sxr.cgi'):
 33            path = os.path.join(config.datadir, path[1:])
 34        else:
 35            path = os.path.join(self.document_root, path[1:])
 36        return path
 37
 38    def is_cgi(self):
 39        """If the path starts with the configured cgi_uri, it is a CGI."""
 40
 41        if self.path.startswith(self.cgi_url):
 42            self.cgi_info = ('/cgi-bin', 'sxr.cgi' + self.path[len(self.cgi_url):])
 43            return True
 44        return False
 45
 46    def run_cgi(self):
 47        """Execute the CGI, either in-process or as a sub-process."""
 48
 49        if not self.sxr_server:
 50            CGIHTTPRequestHandler.run_cgi(self)
 51
 52        else:
 53            command = self.path[len(self.cgi_url) + 1:]
 54            i = command.rfind('?')
 55            if i >= 0:
 56                command, query = command[:i], command[i+1:]
 57            else:
 58                query = ''
 59            if self.debug: print command, query
 60            arguments = cgi.parse_qs(query)
 61            if self.debug: print arguments
 62            self.send_response(200, 'Script output follows')
 63            self.send_header('Content-type', 'text/html')
 64            self.end_headers()
 65            if command == 'file':
 66                pattern = arguments.get('string', [])
 67                self.wfile.write(self.sxr_server.search_file(pattern[0]))
 68            elif command == 'ident':
 69                name = arguments.get('string', [])
 70                qualified = arguments.has_key('full')
 71                self.wfile.write(self.sxr_server.search_ident(name[0], qualified))
 72
 73
 74
 75def usage():
 76   print 'Usage : %s [options]'%'sxr-server'
 77   print """
 78List of options:
 79
 80  -h, --help             Display usage summary
 81  -V, --version          Display version information.
 82  -d, --debug            print debug output
 83  -p, --port             port to listen for requests
 84  -r, --document_root    document root, i.e. top level directory for static files
 85  -u, --url              base url under which to reach sxr.cgi
 86  -s, --src              base url under which to reach source files
 87  --cgi                  use cgi script instead of in-process SXRServer (for testing)
 88"""
 89
 90def run():
 91
 92    port = 8000
 93    env = {}
 94    opts, args = getopt.getopt(sys.argv[1:],
 95                               'p:r:u:s:dhV',
 96                               ['port=', 'document_root=', 'url=', 'src=', 'cgi',
 97                                'debug', 'help', 'version'])
 98    cgi = False
 99    for o, a in opts:
100        if o in ['-h', '--help']:
101            usage()
102            sys.exit(0)
103        elif o in ['-V', '--version']:
104            print 'sxr-server version %s (revision %s)'%(config.version, config.revision)
105            sys.exit(0)
106        elif o in ['-p', '--port']:
107            port = int(a)
108        elif o in ['-r', '--document_root']:
109            env['SXR_ROOT_DIR'] = a
110            SXRConfig.document_root = a
111        elif o in ['-u', '--url']:
112            env['SXR_CGI_URL'] = a
113            SXRConfig.cgi_url = a
114        elif o in ['-s', '--src']:
115            env['SXR_SRC_URL'] = a
116            SXRConfig.src_url = a
117        elif o in ['-d', '--debug']:
118            SXRConfig.debug = True
119        elif o == '--cgi':
120            cgi = True
121
122    if cgi:
123        # For testing purposes only: run ordinary http server that invokes
124        # sxr.cgi for appropriate URLs.
125        os.environ.update(env)
126        httpd = HTTPServer(('', port), RequestHandler)
127    else:
128        # Instantiate an SXRServer object, and set up a request handler that
129        # calls into it.
130        SXRConfig.sxr_server = SXRServer(SXRConfig.document_root,
131                                         SXRConfig.cgi_url,
132                                         SXRConfig.src_url,
133                                         os.path.join(SXRConfig.document_root, 'sxr-template.html'))
134        httpd = HTTPServer(('', port), RequestHandler)
135
136    print 'SXR server running, please connect to http://%s:%d ...'%(socket.gethostname(), port)
137    try:
138        httpd.serve_forever()
139    except KeyboardInterrupt:
140        print 'Keyboard Interrupt: exiting'
141
142if __name__ == '__main__':
143    run()
144