Commits

Gordon McGregor  committed c0417a5

first checkin

  • Participants

Comments (0)

Files changed (4)

+Pygments-server is written and maintained by Gordon McGregor (gordon.mcgregor@verilab.com)
+Copyright (c) 2006-2011 by the respective authors (see AUTHORS file).
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+* Redistributions of source code must retain the above copyright
+  notice, this list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright
+  notice, this list of conditions and the following disclaimer in the
+  documentation and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+A modified version of the SimpleHTTPRequestHandler to serve source code highlighted versions of files that are understood by Pygments (http://pygments.org)
+
+run the script in the root directory of the source tree that you wish to browse.  Connect to http://localhost:8000 and
+navigate the tree.  Files that can be displayed should be displayed with appropriate formating.
+
+Change the server address at line 107 if you want to host it somewhere other than localhost.  The port can be changed on the commandline (pygments-server.py <portnumber>) when running the script.
+
+May not correctly handle some non-ASCII encodings.  
+
+Gordon
+gordon.mcgregor@verilab.com
+
+

File pygments-server.py

+from SimpleHTTPServer import SimpleHTTPRequestHandler
+from pygments import highlight, lexers
+from pygments.formatters import HtmlFormatter
+from pygments.lexers import PythonLexer, ClassNotFound
+import BaseHTTPServer
+import BaseHTTPServer
+import cgi
+import mimetypes
+import os
+import posixpath
+import shutil
+import sys
+import time
+import urllib
+import urlparse
+
+try:
+    from cStringIO import StringIO
+except ImportError:
+    from StringIO import StringIO
+    
+
+class PygmentsHandler(SimpleHTTPRequestHandler):
+    
+    
+    def do_GET(self):
+        """Serve a GET request."""
+        f = self.send_head()
+        if f:
+            self.copyfile(f, self.wfile)
+            f.close()
+
+    def do_HEAD(self):
+        """Serve a HEAD request."""
+        f = self.send_head()
+        if f:
+            f.close()
+                
+    def send_head(self):
+        """Common code for GET and HEAD commands.
+
+        This sends the response code and MIME headers.
+
+        Return value is either a file object (which has to be copied
+        to the outputfile by the caller unless the command was HEAD,
+        and must be closed by the caller under all circumstances), or
+        None, in which case the caller has nothing further to do.
+
+        """
+        path = self.translate_path(self.path)
+        f = None
+        if os.path.isdir(path):
+            if not self.path.endswith('/'):
+                # redirect browser - doing basically what apache does
+                self.send_response(301)
+                self.send_header("Location", self.path + "/")
+                self.end_headers()
+                return None
+            for index in "index.html", "index.htm":
+                index = os.path.join(path, index)
+                if os.path.exists(index):
+                    path = index
+                    break
+            else:
+                return self.list_directory(path)
+        ctype = self.guess_type(path)
+        
+        try:         
+            lexer = lexers.guess_lexer_for_filename(path,'')
+            if lexer:
+                result = StringIO()
+                highlight(open(path, 'rb').read(), lexer, HtmlFormatter(full=True), result)   
+                self.send_response(200)
+                self.send_header("Content-type", 'text/html; charset=utf-8')
+                self.send_header("Content-Length", str(result.tell()))
+                result.seek(0)
+                self.end_headers()
+                
+                return result
+            else:
+                f = open(path, 'rb')
+        except ClassNotFound:
+            print 'no lexer'
+	    f = open(path, 'rb')
+            pass   
+        except IOError:
+            self.send_error(404, "File not found")
+            return None
+        
+        self.send_response(200)
+        self.send_header("Content-type", ctype)
+        fs = os.fstat(f.fileno())
+        self.send_header("Content-Length", str(fs[6]))
+        self.send_header("Last-Modified", self.date_time_string(fs.st_mtime))
+        self.end_headers()
+        return f
+
+
+HandlerClass = PygmentsHandler
+ServerClass  = BaseHTTPServer.HTTPServer
+Protocol     = "HTTP/1.0"
+
+if sys.argv[1:]:
+    port = int(sys.argv[1])
+else:
+    port = 8000
+server_address = ('127.0.0.1', port)
+
+HandlerClass.protocol_version = Protocol
+httpd = ServerClass(server_address, HandlerClass)
+
+sa = httpd.socket.getsockname()
+print "Serving HTTP on", sa[0], "port", sa[1], "..."
+httpd.serve_forever()
+