py3: src/Tools: python3 diff, 1. part

issue 0000995
This commit is contained in:
looooo
2017-05-30 16:13:55 +02:00
committed by wmayer
parent 70a9cce767
commit cf62d45931
7 changed files with 104 additions and 69 deletions

View File

@@ -25,11 +25,11 @@ out.write("const char " + fn[:-3] + "[] =")
for line in lines:
# remove new line
line2 = string.rstrip(line)
line2 = line.rstrip()
# replace special chars
line2 = string.replace(line2,'\\','\\\\')
line2 = string.replace(line2,'\"','\\\"')
line2 = string.replace(line2,"\'","\\\'")
line2 = line2.replace('\\','\\\\')
line2 = line2.replace('\"','\\\"')
line2 = line2.replace("\'","\\\'")
# output

View File

@@ -12,7 +12,10 @@ import os,sys,string,re,time,getopt
import xml.sax
import xml.sax.handler
import xml.sax.xmlreader
import StringIO
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
# SAX handler to parse the subversion output
class SvnHandler(xml.sax.handler.ContentHandler):
@@ -56,14 +59,14 @@ class VersionControl:
return False
def printInfo(self):
print ""
print("")
def writeVersion(self, lines):
content=[]
for line in lines:
line = string.replace(line,'$WCREV$',self.rev)
line = string.replace(line,'$WCDATE$',self.date)
line = string.replace(line,'$WCURL$',self.url)
line = line.replace('$WCREV$',self.rev)
line = line.replace('$WCDATE$',self.date)
line = line.replace('$WCURL$',self.url)
content.append(line)
return content
@@ -78,7 +81,7 @@ class UnknownControl(VersionControl):
return True
def printInfo(self):
print "Unknown version control"
print("Unknown version control")
class DebianChangelog(VersionControl):
def extractInfo(self, srcdir):
@@ -101,7 +104,7 @@ class DebianChangelog(VersionControl):
return True
def printInfo(self):
print "debian/changelog"
print("debian/changelog")
class BazaarControl(VersionControl):
def extractInfo(self, srcdir):
@@ -121,7 +124,7 @@ class BazaarControl(VersionControl):
return True
def printInfo(self):
print "bazaar"
print("bazaar")
class GitControl(VersionControl):
#http://www.hermanradtke.com/blog/canonical-version-numbers-with-git/
@@ -253,7 +256,7 @@ class GitControl(VersionControl):
origin = None #remote for the blessed master
for fetchurl in ("git@github.com:FreeCAD/FreeCAD.git",\
"https://github.com/FreeCAD/FreeCAD.git"):
for key,url in self.remotes.iteritems():
for key,url in self.remotes.items():
if fetchurl in url:
origin = key
break
@@ -283,7 +286,7 @@ class GitControl(VersionControl):
return True
def printInfo(self):
print "git"
print("git")
def writeVersion(self, lines):
content = VersionControl.writeVersion(self, lines)
@@ -297,7 +300,7 @@ class MercurialControl(VersionControl):
return False
def printInfo(self):
print "mercurial"
print("mercurial")
class Subversion(VersionControl):
def extractInfo(self, srcdir):
@@ -322,8 +325,8 @@ class Subversion(VersionControl):
self.date = handler.mapping["Date"]
self.date = self.date[:19]
#Same format as SubWCRev does
self.date = string.replace(self.date,'T',' ')
self.date = string.replace(self.date,'-','/')
self.date = self.date.replace('T',' ')
self.date = self.date.replace('-','/')
#Date is given as GMT. Now we must convert to local date.
m=time.strptime(self.date,"%Y/%m/%d %H:%M:%S")
@@ -353,7 +356,7 @@ class Subversion(VersionControl):
return True
def printInfo(self):
print "subversion"
print("subversion")
def main():

View File

@@ -39,14 +39,14 @@ def generate(filename,path):
Module.path = path
Module.module = GenerateModelInst.Module[0]
Module.Generate()
print "Done generating: " + GenerateModelInst.Module[0].Name
print("Done generating: " + GenerateModelInst.Module[0].Name)
else:
Export = generateTemplates.templateClassPyExport.TemplateClassPyExport()
Export.path = path+"/"
Export.path = path+"/"
Export.dirname = os.path.dirname(filename)+"/";
Export.export = GenerateModelInst.PythonExport[0]
Export.Generate()
print "Done generating: " + GenerateModelInst.PythonExport[0].Name
print("Done generating: " + GenerateModelInst.PythonExport[0].Name)
@@ -55,42 +55,44 @@ def generate(filename,path):
def main():
defaultPath = ""
class generateOutput:
def write(self, data):
pass
sys.stdout=generateOutput()
try:
opts, args = getopt.getopt(sys.argv[1:], "ho:", ["help","outputPath="])
except getopt.GetoptError:
# print help information and exit:
sys.stderr.write(Usage)
sys.exit(2)
defaultPath = ""
class generateOutput:
def write(self, data):
pass
def flush(self): # mandatory for file-like objects
pass
sys.stdout=generateOutput()
try:
opts, args = getopt.getopt(sys.argv[1:], "ho:", ["help","outputPath="])
except getopt.GetoptError:
# print help information and exit:
sys.stderr.write(Usage)
sys.exit(2)
# checking on the options
for o, a in opts:
if o in ("-h", "--help"):
sys.stderr.write(Usage)
sys.exit()
if o in ("-o", "--outputPath"):
defaultPath = a
# checking on the options
for o, a in opts:
if o in ("-h", "--help"):
sys.stderr.write(Usage)
sys.exit()
if o in ("-o", "--outputPath"):
defaultPath = a
# runing through the files
if (len(args) ==0):
#sys.stderr.write(Usage)
generate("../Mod/PartDesign/PartDesign_Model.xml")
else:
for i in args:
filename = os.path.abspath(i)
if(defaultPath == ""):
head,tail = os.path.split(filename)
print head,tail
generate(filename,head)
else:
generate(filename,defaultPath)
# runing through the files
if (len(args) ==0):
#sys.stderr.write(Usage)
generate("../Mod/PartDesign/PartDesign_Model.xml")
else:
for i in args:
filename = os.path.abspath(i)
if(defaultPath == ""):
head,tail = os.path.split(filename)
print(head,tail)
generate(filename,head)
else:
generate(filename,defaultPath)
if __name__ == "__main__":
main()
main()

View File

@@ -0,0 +1,4 @@
# remove this once python2 support has stopped
def __exec_new__(text, globals, locals):
exec(text, globals, locals)

View File

@@ -0,0 +1,4 @@
# remove this file once the python2 support has stopped
def __exec_old__(text, globals, locals):
exec text in globals, locals

View File

@@ -7,6 +7,8 @@
# WARNING! All changes made in this file will be lost!
#
from __future__ import print_function # this allows py2 to print(str1,str2) correctly
import sys
import getopt
from xml.dom import minidom
@@ -1808,7 +1810,7 @@ class SaxGeneratemodelHandler(handler.ContentHandler):
self.locator = locator
def showError(self, msg):
print '*** (showError):', msg
print('*** (showError):', msg)
sys.exit(-1)
def startElement(self, name, attrs):
@@ -2266,7 +2268,7 @@ Options:
"""
def usage():
print USAGE_TEXT
print(USAGE_TEXT)
sys.exit(-1)
@@ -2295,10 +2297,10 @@ def parseSelect(inFileName):
except StopIteration:
topElementName = documentHandler.getTopElementName()
if topElementName is None:
raise RuntimeError, 'no top level element'
raise RuntimeError('no top level element')
topElementName = topElementName.replace('-', '_').replace(':', '_')
if topElementName not in globals():
raise RuntimeError, 'no class for top element: %s' % topElementName
raise RuntimeError('no class for top element: %s' % topElementName)
topElement = globals()[topElementName]
infile.seek(0)
doc = minidom.parse(infile)

View File

@@ -2,15 +2,31 @@
# -*- coding: utf-8 -*-
# (c) 2007 Jürgen Riegel
from __future__ import print_function # this allows py2 to print(str1,str2) correctly
import os, errno
def ensureDir(path,mode=0777):
def temporary_exec(text, globals, locals):
"""this function is a dirty hack to allow using the copier from
python2 and python3. Once the support of python2 has stopped
feel free to remove this function and use the std exec function
instead"""
# maybe this should be fixed by rewriting the generators.
if sys.version_info[0] < 3:
from .__exec_old import __exec_old__
__exec_old__(text, globals, locals)
else:
from .__exec_new import __exec_new__
__exec_new__(text, globals, locals)
def ensureDir(path,mode=0o777):
try:
os.makedirs(path,mode)
except OSError, err:
except OSError(err):
# raise an error unless it's about a alredy existing directory
print "Dir Exist"
print("Dir Exist")
#if errno != 17 or not os.path.isdir(path):
# raise
@@ -43,7 +59,7 @@ class copier:
"Main copy method: process lines [i,last) of block"
def repl(match, self=self):
"return the eval of a found expression, for replacement"
# uncomment for debug: print '!!! replacing',match.group(1)
# uncomment for debug: print ('!!! replacing',match.group(1))
expr = self.preproc(match.group(1), 'eval')
try: return str(eval(expr, self.globals, self.locals))
except: return str(self.handle(expr))
@@ -74,11 +90,14 @@ class copier:
j=j+1
stat = self.preproc(stat, 'exec')
stat = '%s _cb(%s,%s)' % (stat,i+1,j)
# for debugging, uncomment...: print "-> Executing: {"+stat+"}"
exec stat in self.globals,self.locals
# for debugging, uncomment...: print("-> Executing: {"+stat+"}")
temporary_exec(stat, self.globals, self.locals)
i=j+1
else: # normal line, just copy with substitution
self.ouf.write(self.regex.sub(repl,line))
try:
self.ouf.write(self.regex.sub(repl, line).encode("utf8"))
except TypeError:
self.ouf.write(self.regex.sub(repl, line))
i=i+1
def __init__(self, regex=_never, dict={},
restat=_never, restend=_never, recont=_never,
@@ -86,6 +105,7 @@ class copier:
"Initialize self's attributes"
self.regex = regex
self.globals = dict
self.globals['sys'] = sys
self.locals = { '_cb':self.copyblock }
self.restat = restat
self.restend = restend
@@ -136,8 +156,8 @@ After all, @x@ is rather small!
Also, @i@ times @x@ is @i*x@.
-
One last, plain line at the end.""".split('\n')]
print "*** input:"
print ''.join(lines_block)
print "*** output:"
print("*** input:")
print(''.join(lines_block))
print("*** output:")
cop.copy(lines_block)