Description: Switch to Python 3.
Author: Bas Couwenberg <sebastic@debian.org>
Forwarded: not-needed

--- a/build/build.py
+++ b/build/build.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 
 import sys
 import os
@@ -12,32 +12,32 @@ def build(config_file = None, output_fil
         import jsmin
         have_compressor.append("jsmin")
     except ImportError:
-        print "No jsmin"
+        print("No jsmin")
     try:
         # tools/closure_library_jscompiler.py from: 
         #       http://code.google.com/p/closure-library/source/browse/trunk/closure/bin/build/jscompiler.py
         import closure_library_jscompiler as closureCompiler
         have_compressor.append("closure")
-    except Exception, E:
-        print "No closure (%s)" % E
+    except Exception as E:
+        print("No closure (%s)" % E)
     try:
         import closure_ws
         have_compressor.append("closure_ws")
     except ImportError:
-        print "No closure_ws"
+        print("No closure_ws")
     
     try:
         import minimize
         have_compressor.append("minimize")
     except ImportError:
-        print "No minimize"
+        print("No minimize")
 
     try:
         import uglify_js
         uglify_js.check_available()
         have_compressor.append("uglify-js")
-    except Exception, E:
-        print "No uglify-js (%s)" % E
+    except Exception as E:
+        print("No uglify-js (%s)" % E)
 
     use_compressor = None
     if options.compressor and options.compressor in have_compressor:
@@ -57,14 +57,14 @@ def build(config_file = None, output_fil
     if output_file:
         outputFilename = output_file
 
-    print "Merging libraries."
+    print("Merging libraries.")
     try:
         if use_compressor == "closure" or use_compressor == 'uglify-js':
             sourceFiles = mergejs.getNames(sourceDirectory, configFilename)
         else:
             merged = mergejs.run(sourceDirectory, None, configFilename)
-    except mergejs.MissingImport, E:
-        print "\nAbnormal termination."
+    except mergejs.MissingImport as E:
+        print("\nAbnormal termination.")
         sys.exit("ERROR: %s" % E)
 
     if options.amdname:
@@ -73,33 +73,33 @@ def build(config_file = None, output_fil
         options.amdname = ""
         
     if options.amd == 'pre':
-        print "\nAdding AMD function."
+        print("\nAdding AMD function.")
         merged = "define(%sfunction(){%sreturn OpenLayers;});" % (options.amdname, merged)
     
-    print "Compressing using %s" % use_compressor
+    print("Compressing using %s" % use_compressor)
     if use_compressor == "jsmin":
         minimized = jsmin.jsmin(merged)
     elif use_compressor == "minimize":
         minimized = minimize.minimize(merged)
     elif use_compressor == "closure_ws":
         if len(merged) > 1000000: # The maximum file size for this web service is 1000 KB.
-            print "\nPre-compressing using jsmin"
+            print("\nPre-compressing using jsmin")
             merged = jsmin.jsmin(merged)
-        print "\nIs being compressed using Closure Compiler Service."
+        print("\nIs being compressed using Closure Compiler Service.")
         try:
             minimized = closure_ws.minimize(merged)
-        except Exception, E:
-            print "\nAbnormal termination."
+        except Exception as E:
+            print("\nAbnormal termination.")
             sys.exit("ERROR: Closure Compilation using Web service failed!\n%s" % E)
         if len(minimized) <= 2:
-            print "\nAbnormal termination due to compilation errors."
+            print("\nAbnormal termination due to compilation errors.")
             sys.exit("ERROR: Closure Compilation using Web service failed!")
         else:
-            print "Closure Compilation using Web service has completed successfully."
+            print("Closure Compilation using Web service has completed successfully.")
     elif use_compressor == "closure":
         jscompilerJar = "../tools/closure-compiler.jar"
         if not os.path.isfile(jscompilerJar):
-            print "\nNo closure-compiler.jar; read README.txt!"
+            print("\nNo closure-compiler.jar; read README.txt!")
             sys.exit("ERROR: Closure Compiler \"%s\" does not exist! Read README.txt" % jscompilerJar)
         minimized = closureCompiler.Compile(
             jscompilerJar, 
@@ -111,35 +111,42 @@ def build(config_file = None, output_fil
             ]
         )
         if minimized is None:
-            print "\nAbnormal termination due to compilation errors." 
+            print("\nAbnormal termination due to compilation errors.")
             sys.exit("ERROR: Closure Compilation failed! See compilation errors.") 
-        print "Closure Compilation has completed successfully."
+        print("Closure Compilation has completed successfully.")
     elif use_compressor == "uglify-js":
         minimized = uglify_js.compile(sourceFiles)
         if minimized is None:
-            print "\nAbnormal termination due to compilation errors."
+            print("\nAbnormal termination due to compilation errors.")
             sys.exit("ERROR: Uglify JS compilation failed! See compilation errors.")
 
-        print "Uglify JS compilation has completed successfully."
+        print("Uglify JS compilation has completed successfully.")
 
     else: # fallback
         minimized = merged 
 
     if options.amd == 'post':
-        print "\nAdding AMD function."
+        print("\nAdding AMD function.")
         minimized = "define(%sfunction(){%sreturn OpenLayers;});" % (options.amdname, minimized)
     
     if options.status:
-        print "\nAdding status file."
-        minimized = "// status: " + file(options.status).read() + minimized
+        print("\nAdding status file.")
+        status = ''
+        with open(options.status) as f:
+            status = f.read()
+        minimized = "// status: " + status + minimized
     
-    print "\nAdding license file."
-    minimized = file("license.txt").read() + minimized
+    print("\nAdding license file.")
+    license = ''
+    with open("license.txt") as f:
+        license = f.read()
+    minimized = license + minimized
+
+    print("Writing to %s." % outputFilename)
+    with open(outputFilename, "w") as f:
+        f.write(minimized)
 
-    print "Writing to %s." % outputFilename
-    file(outputFilename, "w").write(minimized)
-
-    print "Done."
+    print("Done.")
 
 if __name__ == '__main__':
   opt = optparse.OptionParser(usage="%s [options] [config_file] [output_file]\n  Default config_file is 'full.cfg', Default output_file is 'OpenLayers.js'")
@@ -155,4 +162,4 @@ if __name__ == '__main__':
   elif len(args) == 2:
     build(args[0], args[1], options=options)
   else:
-    print "Wrong number of arguments"
\ No newline at end of file
+    print("Wrong number of arguments")
--- a/build/buildUncompressed.py
+++ b/build/buildUncompressed.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 
 import sys
 sys.path.append("../tools")
@@ -14,12 +14,16 @@ if len(sys.argv) > 1:
 if len(sys.argv) > 2:
     outputFilename = sys.argv[2]
 
-print "Merging libraries."
+print("Merging libraries.")
 merged = mergejs.run(sourceDirectory, None, configFilename)
-print "Adding license file."
-merged = file("license.txt").read() + merged
+print("Adding license file.")
+license = ''
+with open("license.txt") as f:
+    license = f.read()
+merged = license + merged
+
+print("Writing to %s." % outputFilename)
+with open(outputFilename, "w") as f:
+    f.write(merged)
 
-print "Writing to %s." % outputFilename
-file(outputFilename, "w").write(merged)
-
-print "Done."
+print("Done.")
--- a/tools/closure_ws.py
+++ b/tools/closure_ws.py
@@ -1,4 +1,4 @@
-#!/usr/bin/python
+#!/usr/bin/python3
 
 import httplib, urllib, sys
 import time
@@ -24,5 +24,5 @@ def minimize(code):
     conn.close()
     if data.startswith("Error"):
         raise Exception(data)
-    print "%.3f seconds to compile" % (time.time() - t) 
+    print("%.3f seconds to compile" % (time.time() - t))
     return data
--- a/tools/mergejs.py
+++ b/tools/mergejs.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 #
 # Merge multiple JavaScript source code files into one.
 #
@@ -86,7 +86,7 @@ def usage(filename):
     """
     Displays a usage message.
     """
-    print "%s [-c <config file>] <output.js> <directory> [...]" % filename
+    print("%s [-c <config file>] <output.js> <directory> [...]" % filename)
 
 
 class Config:
@@ -181,9 +181,9 @@ def run (sourceDirectory, outputFilename
     ## Import file source code
     ## TODO: Do import when we walk the directories above?
     for filepath in allFiles:
-        print "Importing: %s" % filepath
+        print("Importing: %s" % filepath)
         fullpath = os.path.join(sourceDirectory, filepath).strip()
-        content = open(fullpath, "U").read() # TODO: Ensure end of line @ EOF?
+        content = open(fullpath, "r").read() # TODO: Ensure end of line @ EOF?
         files[filepath] = SourceFile(filepath, content, cfg.exclude) # TODO: Chop path?
 
     print
@@ -197,32 +197,34 @@ def run (sourceDirectory, outputFilename
         complete = True
 
         ## Resolve the dependencies
-        print "Resolution pass %s... " % resolution_pass
+        print("Resolution pass %s... " % resolution_pass)
         resolution_pass += 1 
 
-        for filepath, info in files.items():
+        for filepath in list(files):
+            info = files[filepath]
             for path in info.requires:
-                if not files.has_key(path):
+                if path not in files:
                     complete = False
                     fullpath = os.path.join(sourceDirectory, path).strip()
                     if os.path.exists(fullpath):
-                        print "Importing: %s" % path
-                        content = open(fullpath, "U").read() # TODO: Ensure end of line @ EOF?
+                        print("Importing: %s" % path)
+                        content = open(fullpath, "r").read() # TODO: Ensure end of line @ EOF?
                         files[path] = SourceFile(path, content, cfg.exclude) # TODO: Chop path?
                     else:
                         raise MissingImport("File '%s' not found (required by '%s')." % (path, filepath))
         
     # create dictionary of dependencies
     dependencies = {}
-    for filepath, info in files.items():
+    for filepath in files:
+        info = files[filepath]
         dependencies[filepath] = info.requires
 
-    print "Sorting..."
+    print("Sorting...")
     order = toposort(dependencies) #[x for x in toposort(dependencies)]
 
     ## Move forced first and last files to the required position
     if cfg:
-        print "Re-ordering files..."
+        print("Re-ordering files...")
         order = cfg.forceFirst + [item
                      for item in order
                      if ((item not in cfg.forceFirst) and
@@ -236,30 +238,30 @@ def run (sourceDirectory, outputFilename
     if returnAsListOfNames:
         for fp in order:
             fName = os.path.normpath(os.path.join(sourceDirectory, fp)).replace("\\","/")
-            print "Append: ", fName
+            print("Append: ", fName)
             f = files[fp]
             for fExclude in f.excludedFiles: 
-                print "  Required file \"%s\" is excluded." % fExclude 
+                print("  Required file \"%s\" is excluded." % fExclude)
             result.append(fName)
-        print "\nTotal files: %d " % len(result)
+        print("\nTotal files: %d " % len(result))
         return result
         
     # Return as merged source code
     for fp in order:
         f = files[fp]
-        print "Exporting: ", f.filepath
+        print("Exporting: ", f.filepath)
         for fExclude in f.excludedFiles: 
-            print "  Required file \"%s\" is excluded." % fExclude 
+            print("  Required file \"%s\" is excluded." % fExclude)
         result.append(HEADER % f.filepath)
         source = f.source
         result.append(source)
         if not source.endswith("\n"):
             result.append("\n")
 
-    print "\nTotal files merged: %d " % len(files)
+    print("\nTotal files merged: %d " % len(files))
 
     if outputFilename:
-        print "\nGenerating: %s" % (outputFilename)
+        print("\nGenerating: %s" % (outputFilename))
         open(outputFilename, "w").write("".join(result))
     return "".join(result)
 
@@ -282,6 +284,6 @@ if __name__ == "__main__":
     configFile = None
     if options and options[0][0] == "-c":
         configFile = options[0][1]
-        print "Parsing configuration file: %s" % filename
+        print("Parsing configuration file: %s" % filename)
 
     run( sourceDirectory, outputFilename, configFile )
--- a/tools/oldot.py
+++ b/tools/oldot.py
@@ -20,7 +20,7 @@ def run():
                 cls = "OpenLayers.%s" % filepath.strip(".js").replace("/", ".")
                 allFiles.append([cls, parents])
     return allFiles
-print """
+print("""
 digraph name {
   fontname = "Helvetica"
   fontsize = 8
@@ -31,13 +31,13 @@ digraph name {
     fontsize = 8
     shape = "plaintext"
   ]
-"""
+""")
 
 for i in run():
-    print i[0].replace(".", "_")
+    print(i[0].replace(".", "_"))
     for item in i[1]:
         if not item: continue
-        print "%s -> %s" % (i[0].replace(".","_"), item.replace(".", "_"))
-    print "; "
+        print("%s -> %s" % (i[0].replace(".","_"), item.replace(".", "_")))
+    print("; ")
 
-print """}"""
+print("""}""")
--- a/tools/release.sh
+++ b/tools/release.sh
@@ -45,7 +45,7 @@ rm ../tools/closure-compiler.jar
 
 cd ..
 cd tools
-python exampleparser.py
+python3 exampleparser.py
 cd ..
 for i in google ie6-style style style.mobile; do
     csstidy theme/default/$i.css --template=highest theme/default/$i.tidy.css
--- a/examples/proxy.cgi
+++ b/examples/proxy.cgi
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 
 
 """This is a blind proxy that we use to get around browser
@@ -9,9 +9,12 @@ people can use this proxy to browse the
 with it.  It only loads pages via http and https, but it can load any
 content type. It supports GET and POST requests."""
 
-import urllib2
 import cgi
-import sys, os
+import os
+import sys
+import urllib
+
+import requests
 
 # Designed to prevent Open Proxy type stuff.
 
@@ -20,62 +23,65 @@ allowedHosts = ['www.openlayers.org', 'o
                 'prototype.openmnnd.org', 'geo.openplans.org',
                 'sigma.openplans.org', 'demo.opengeo.org',
                 'www.openstreetmap.org', 'sample.azavea.com',
-                'v2.suite.opengeo.org', 'v-swe.uni-muenster.de:8080',
+                'v2.suite.opengeo.org', 'v-swe.uni-muenster.de:8080', 
                 'vmap0.tiles.osgeo.org', 'www.openrouteservice.org',
                 'maps.wien.gv.at']
 
+default_url = "http://www.openlayers.org"
+
 method = os.environ["REQUEST_METHOD"]
 
 if method == "POST":
     qs = os.environ["QUERY_STRING"]
-    d = cgi.parse_qs(qs)
-    if d.has_key("url"):
+    d = urllib.parse.parse_qs(qs)
+    if "url" in d:
         url = d["url"][0]
     else:
-        url = "http://www.openlayers.org"
+        url = default_url
 else:
     fs = cgi.FieldStorage()
-    url = fs.getvalue('url', "http://www.openlayers.org")
+    url = fs.getvalue('url', default_url)
 
 try:
     host = url.split("/")[2]
     if allowedHosts and not host in allowedHosts:
-        print "Status: 502 Bad Gateway"
-        print "Content-Type: text/plain"
-        print
-        print "This proxy does not allow you to access that location (%s)." % (host,)
-        print
-        print os.environ
+        print("Status: 502 Bad Gateway")
+        print("Content-Type: text/plain")
+        print("")
+        print("This proxy does not allow you to access that location (%s)." % (host,))
+        print("")
+        print(os.environ)
   
     elif url.startswith("http://") or url.startswith("https://"):
     
         if method == "POST":
+            content_type = 'text/plain'
+            if 'CONTENT_TYPE' in os.environ:
+                content_type = os.environ["CONTENT_TYPE"]
+
             length = int(os.environ["CONTENT_LENGTH"])
-            headers = {"Content-Type": os.environ["CONTENT_TYPE"]}
+            headers = {"Content-Type": content_type}
             body = sys.stdin.read(length)
-            r = urllib2.Request(url, body, headers)
-            y = urllib2.urlopen(r)
+
+            r = requests.post(url, data=body, headers=headers)
         else:
-            y = urllib2.urlopen(url)
+            r = requests.get(url)
         
         # print content type header
-        i = y.info()
-        if i.has_key("Content-Type"):
-            print "Content-Type: %s" % (i["Content-Type"])
+        if "Content-Type" in r.headers:
+            print("Content-Type: %s" % (r.headers["Content-Type"]))
         else:
-            print "Content-Type: text/plain"
-        print
-        
-        print y.read()
+            print("Content-Type: text/plain")
+        print("")
         
-        y.close()
+        print(r.text)
     else:
-        print "Content-Type: text/plain"
-        print
-        print "Illegal request."
-
-except Exception, E:
-    print "Status: 500 Unexpected Error"
-    print "Content-Type: text/plain"
-    print 
-    print "Some unexpected error occurred. Error text was:", E
+        print("Content-Type: text/plain")
+        print("")
+        print("Illegal request.")
+
+except Exception as E:
+    print("Status: 500 Unexpected Error")
+    print("Content-Type: text/plain")
+    print("")
+    print("Some unexpected error occurred. Error text was:", E)
--- a/tools/toposort.py
+++ b/tools/toposort.py
@@ -20,7 +20,7 @@ class Sorter(object):
     def _visit(self, key):
         if key not in self.visited:
             self.visited.add(key)
-            if not self.dependencies.has_key(key):
+            if key not in self.dependencies:
                 raise MissingDependency(key)
             for depends in self.dependencies[key]:
                 self._visit(depends)
