diff --git a/build/build.py b/build/build.py index 4f5a3294c5..b10750d21e 100755 --- a/build/build.py +++ b/build/build.py @@ -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: @@ -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: @@ -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, @@ -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'") @@ -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") diff --git a/build/buildUncompressed.py b/build/buildUncompressed.py index fd38aa74cd..d3ab5c4e86 100755 --- a/build/buildUncompressed.py +++ b/build/buildUncompressed.py @@ -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.") diff --git a/tools/closure_library_jscompiler.py b/tools/closure_library_jscompiler.py index fd1882fdb3..b61a2194be 100644 --- a/tools/closure_library_jscompiler.py +++ b/tools/closure_library_jscompiler.py @@ -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): diff --git a/tools/closure_ws.py b/tools/closure_ws.py index 3bf925a729..c87c39a345 100644 --- a/tools/closure_ws.py +++ b/tools/closure_ws.py @@ -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'), @@ -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 diff --git a/tools/exampleparser.py b/tools/exampleparser.py index 3211469488..7f5f19b960 100755 --- a/tools/exampleparser.py +++ b/tools/exampleparser.py @@ -47,7 +47,7 @@ def getExampleHtml(path): """ returns html of a specific example """ - print '.', + print('.') f = open(path) html = f.read() f.close() @@ -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: @@ -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'] @@ -226,7 +226,7 @@ def wordIndex(examples): exampleList.append(tagvalues) - print + print() exampleList.sort(key=lambda x:x['example'].lower()) @@ -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') diff --git a/tools/jsmin.py b/tools/jsmin.py index d1887908cd..f02269128a 100755 --- a/tools/jsmin.py +++ b/tools/jsmin.py @@ -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) diff --git a/tools/mergejs.py b/tools/mergejs.py index 1b26f2ec3f..93ad705739 100755 --- a/tools/mergejs.py +++ b/tools/mergejs.py @@ -40,6 +40,7 @@ import re import os import sys +from collections import OrderedDict SUFFIX_JAVASCRIPT = ".js" @@ -86,7 +87,7 @@ def usage(filename): """ Displays a usage message. """ - print "%s [-c ] [...]" % filename + print("%s [-c ] [...]" % filename) class Config: @@ -176,17 +177,17 @@ def run (sourceDirectory, outputFilename = None, configFile = None, ## Header inserted at the start of each file in the output HEADER = "/* " + "=" * 70 + "\n %s\n" + " " + "=" * 70 + " */\n\n" - files = {} + files = OrderedDict() ## 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? files[filepath] = SourceFile(filepath, content, cfg.exclude) # TODO: Chop path? - print + print() from toposort import toposort @@ -197,38 +198,38 @@ def run (sourceDirectory, outputFilename = None, configFile = None, 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, info in list(files.items()): for path in info.requires: - if not files.has_key(path): + if not path in files: complete = False fullpath = os.path.join(sourceDirectory, path).strip() if os.path.exists(fullpath): - print "Importing: %s" % path + print("Importing: %s" % path) content = open(fullpath, "U").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 = {} + dependencies = OrderedDict() for filepath, info in files.items(): 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 (item not in cfg.forceLast))] + cfg.forceLast - print + print() ## Output the files in the determined order result = [] @@ -236,30 +237,30 @@ def run (sourceDirectory, outputFilename = None, configFile = None, if returnAsListOfNames: for fp in order: fName = os.path.normpath(os.path.join(sourceDirectory, fp)).replace("\\","/") - print "Append: ", fName + print("Append: %s" % 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: %s" % 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 +283,6 @@ def run (sourceDirectory, outputFilename = None, configFile = None, 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 ) diff --git a/tools/minimize.py b/tools/minimize.py index 5358bd54a7..8a3de184b9 100644 --- a/tools/minimize.py +++ b/tools/minimize.py @@ -35,7 +35,7 @@ def minimize(data, exclude=None): functions. To add further compression algorithms, simply add functions whose names end in _helper which take a string as input and return a more compressed string as output.""" - for key, item in globals().iteritems(): + for key, item in globals().items(): if key.endswith("_helper"): func_key = key[:-7] if not exclude or not func_key in exclude: @@ -44,4 +44,4 @@ def minimize(data, exclude=None): if __name__ == "__main__": import sys - print minimize(open(sys.argv[1]).read()) + print(minimize(open(sys.argv[1]).read())) diff --git a/tools/oldot.py b/tools/oldot.py index 396fb1779c..9981a94ca2 100644 --- 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 @@ -34,10 +34,10 @@ def run(): """ 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("""}""") diff --git a/tools/shrinksafe.py b/tools/shrinksafe.py index a42e941948..e92d47831a 100755 --- a/tools/shrinksafe.py +++ b/tools/shrinksafe.py @@ -29,7 +29,7 @@ try: sourceFilename = sys.argv[1] except: - print "Usage: %s (|-)" % sys.argv[0] + print("Usage: %s (|-)" % sys.argv[0]) raise SystemExit if sourceFilename == "-": @@ -51,4 +51,4 @@ """ % (BOUNDARY_MARKER, sourceFilename, sourceCode)) ## Deliver the result - print urllib2.urlopen(request).read(), + print(urllib2.urlopen(request).read(),) diff --git a/tools/toposort.py b/tools/toposort.py index ba586ef8b4..232efbdf39 100644 --- a/tools/toposort.py +++ b/tools/toposort.py @@ -20,7 +20,7 @@ def sort(self): def _visit(self, key): if key not in self.visited: self.visited.add(key) - if not self.dependencies.has_key(key): + if not key in self.dependencies: raise MissingDependency(key) for depends in self.dependencies[key]: self._visit(depends)