Skip to content

Commit

Permalink
Merge pull request #1470 from PetrDlouhy/master
Browse files Browse the repository at this point in the history
Python 3 compatibility fixes
  • Loading branch information
ahocevar authored Aug 11, 2016
2 parents 2ae251a + f683c2e commit 75716be
Show file tree
Hide file tree
Showing 11 changed files with 97 additions and 83 deletions.
76 changes: 39 additions & 37 deletions build/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,33 +11,33 @@ def build(config_file = None, output_file = None, options = None):
try:
import jsmin
have_compressor.append("jsmin")
except ImportError:
print "No jsmin"
except ImportError as E:
print("No jsmin (%s)" % E)
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"
except ImportError as E:
print("No closure_ws (%s)" % E)

try:
import minimize
have_compressor.append("minimize")
except ImportError:
print "No minimize"
except ImportError as E:
print("No minimize (%s)" % E)

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:
Expand All @@ -57,14 +57,14 @@ def build(config_file = None, output_file = None, options = None):
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:
Expand All @@ -73,33 +73,33 @@ def build(config_file = None, output_file = None, options = None):
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."
minimized = closure_ws.minimize(merged).decode()
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,
Expand All @@ -109,37 +109,39 @@ def build(config_file = None, output_file = None, options = None):
"--jscomp_error", "checkRegExp", # Also necessary to enable "undefinedVars"
"--jscomp_error", "undefinedVars"
]
)
).decode()
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 (sys.version_info > (3, 0)):
minimized = minimized.decode()
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.")
minimized = "// status: " + open(options.status).read() + minimized

print "\nAdding license file."
minimized = file("license.txt").read() + minimized
print("\nAdding license file.")
minimized = open("license.txt").read() + minimized

print "Writing to %s." % outputFilename
file(outputFilename, "w").write(minimized)
print("Writing to %s." % outputFilename)
open(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'")
Expand All @@ -155,4 +157,4 @@ def build(config_file = None, output_file = None, options = None):
elif len(args) == 2:
build(args[0], args[1], options=options)
else:
print "Wrong number of arguments"
print("Wrong number of arguments")
8 changes: 4 additions & 4 deletions build/buildUncompressed.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@
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."
print("Adding license file.")
merged = file("license.txt").read() + merged

print "Writing to %s." % outputFilename
print("Writing to %s." % outputFilename)
file(outputFilename, "w").write(merged)

print "Done."
print("Done.")
2 changes: 1 addition & 1 deletion tools/closure_library_jscompiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def _GetJavaVersion():
proc = subprocess.Popen(['java', '-version'], stderr=subprocess.PIPE)
unused_stdoutdata, stderrdata = proc.communicate()
version_line = stderrdata.splitlines()[0]
return _VERSION_REGEX.search(version_line).group(1)
return _VERSION_REGEX.search(version_line.decode()).group(1)


def Compile(compiler_jar_path, source_paths, flags=None):
Expand Down
16 changes: 12 additions & 4 deletions tools/closure_ws.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,21 @@
#!/usr/bin/python

import httplib, urllib, sys
try:
import httplib # Python 2
except ImportError:
from http import client as httplib # Python 3
try:
from urllib import urlencode # Python 2
except ImportError:
from urllib.parse import urlencode # Python 3
import sys
import time
# Define the parameters for the POST request and encode them in
# a URL-safe format.

def minimize(code):

params = urllib.urlencode([
params = urlencode([
('js_code', code),
('compilation_level', 'SIMPLE_OPTIMIZATIONS'),
('output_format', 'text'),
Expand All @@ -22,7 +30,7 @@ def minimize(code):
response = conn.getresponse()
data = response.read()
conn.close()
if data.startswith("Error"):
if data.startswith(b"Error"):
raise Exception(data)
print "%.3f seconds to compile" % (time.time() - t)
print("%.3f seconds to compile" % (time.time() - t))
return data
12 changes: 6 additions & 6 deletions tools/exampleparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def getExampleHtml(path):
"""
returns html of a specific example
"""
print '.',
print('.')
f = open(path)
html = f.read()
f.close()
Expand Down Expand Up @@ -192,7 +192,7 @@ def wordIndex(examples):
if __name__ == "__main__":

if missing_deps:
print "This script requires json or simplejson and BeautifulSoup. You don't have them. \n(%s)" % E
print("This script requires json or simplejson and BeautifulSoup. You don't have them. \n(%s)" % E)
sys.exit()

if len(sys.argv) == 3:
Expand All @@ -204,7 +204,7 @@ def wordIndex(examples):

outFile = open(os.path.join(outExampleDir, "example-list.js"), "w")

print 'Reading examples from %s and writing out to %s' % (inExampleDir, outFile.name)
print('Reading examples from %s and writing out to %s' % (inExampleDir, outFile.name))

exampleList = []
docIds = ['title','shortdesc','tags']
Expand All @@ -226,7 +226,7 @@ def wordIndex(examples):

exampleList.append(tagvalues)

print
print()

exampleList.sort(key=lambda x:x['example'].lower())

Expand All @@ -239,11 +239,11 @@ def wordIndex(examples):
outFile.close()

outFeedPath = os.path.join(outExampleDir, feedName);
print "writing feed to %s " % outFeedPath
print("writing feed to %s " % outFeedPath)
atom = open(outFeedPath, 'w')
doc = createFeed(exampleList)
atom.write(doc.toxml())
atom.close()


print 'complete'
print('complete')
5 changes: 4 additions & 1 deletion tools/jsmin.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,10 @@
# SOFTWARE.
# */

from StringIO import StringIO
try:
from StringIO import StringIO # Python 2
except ImportError:
from io import StringIO # Python 3

def jsmin(js):
ins = StringIO(js)
Expand Down
Loading

0 comments on commit 75716be

Please sign in to comment.