Python3 support

* Mostly involves changing print to be a function, and adding
  "from __future__ import print_function" for copatibility.

Change-Id: I3129233726e0116a348753a2e2bb68806a08668c
Signed-off-by: Chirayu Desai <cdesai@cyanogenmod.org>
This commit is contained in:
Chirayu Desai 2013-05-13 13:48:43 +05:30
parent 4deeefb2d3
commit 4c5ee48f47
6 changed files with 59 additions and 46 deletions

View File

@ -15,6 +15,8 @@
# #
# TODO(sop): Be more detailed: version, link to Maven Central # TODO(sop): Be more detailed: version, link to Maven Central
from __future__ import print_function
from collections import defaultdict, deque from collections import defaultdict, deque
import re import re
from shutil import copyfileobj from shutil import copyfileobj
@ -51,9 +53,9 @@ while queue:
continue continue
licenses[dep].add(target) licenses[dep].add(target)
queue.extend(graph[target]) queue.extend(graph[target])
used = sorted(licenses.iterkeys()) used = sorted(licenses.keys())
print """\ print("""\
Gerrit Code Review - Licenses Gerrit Code Review - Licenses
============================= =============================
@ -100,30 +102,30 @@ to be installed by the end-user.
Licenses Licenses
-------- --------
""" """)
for n in used: for n in used:
libs = sorted(licenses[n]) libs = sorted(licenses[n])
name = n[len('//lib:LICENSE-'):] name = n[len('//lib:LICENSE-'):]
print print()
print '[[%s]]' % name print('[[%s]]' % name)
print name print(name)
print '~' * len(name) print('~' * len(name))
print print()
for d in libs: for d in libs:
if d.startswith('//lib:') or d.startswith('//lib/'): if d.startswith('//lib:') or d.startswith('//lib/'):
p = d[len('//lib:'):] p = d[len('//lib:'):]
else: else:
p = d[d.index(':')+1:].lower() p = d[d.index(':')+1:].lower()
print '* ' + p print('* ' + p)
print print()
print '----' print('----')
with open(n[2:].replace(':', '/')) as fd: with open(n[2:].replace(':', '/')) as fd:
copyfileobj(fd, stdout) copyfileobj(fd, stdout)
print '----' print('----')
print """ print("""
GERRIT GERRIT
------ ------
Part of link:index.html[Gerrit Code Review] Part of link:index.html[Gerrit Code Review]
""" """)

View File

@ -1,5 +1,8 @@
#!/usr/bin/env python #!/usr/bin/env python
import commands
from __future__ import print_function
import subprocess
import getopt import getopt
import sys import sys
@ -24,8 +27,8 @@ def main():
try: try:
opts, args = getopt.getopt(sys.argv[1:], '', \ opts, args = getopt.getopt(sys.argv[1:], '', \
['change=', 'project=', 'branch=', 'commit=', 'patchset=']) ['change=', 'project=', 'branch=', 'commit=', 'patchset='])
except getopt.GetoptError, err: except getopt.GetoptError as err:
print 'Error: %s' % (err) print('Error: %s' % (err))
usage() usage()
sys.exit(-1) sys.exit(-1)
@ -41,7 +44,7 @@ def main():
elif arg == '--patchset': elif arg == '--patchset':
patchset = value patchset = value
else: else:
print 'Error: option %s not recognized' % (arg) print('Error: option %s not recognized' % (arg))
usage() usage()
sys.exit(-1) sys.exit(-1)
@ -51,11 +54,11 @@ def main():
sys.exit(-1) sys.exit(-1)
command = 'git cat-file commit %s' % (commit) command = 'git cat-file commit %s' % (commit)
status, output = commands.getstatusoutput(command) status, output = subprocess.getstatusoutput(command)
if status != 0: if status != 0:
print 'Error running \'%s\'. status: %s, output:\n\n%s' % \ print('Error running \'%s\'. status: %s, output:\n\n%s' % \
(command, status, output) (command, status, output))
sys.exit(-1) sys.exit(-1)
commitMessage = output[(output.find('\n\n')+2):] commitMessage = output[(output.find('\n\n')+2):]
@ -74,21 +77,21 @@ def main():
passes(commit) passes(commit)
def usage(): def usage():
print 'Usage:\n' print('Usage:\n')
print sys.argv[0] + ' --change <change id> --project <project name> ' \ print(sys.argv[0] + ' --change <change id> --project <project name> ' \
+ '--branch <branch> --commit <sha1> --patchset <patchset id>' + '--branch <branch> --commit <sha1> --patchset <patchset id>')
def fail( commit, message ): def fail( commit, message ):
command = SSH_COMMAND + FAILURE_SCORE + ' -m \\\"' \ command = SSH_COMMAND + FAILURE_SCORE + ' -m \\\"' \
+ _shell_escape( FAILURE_MESSAGE + '\n\n' + message) \ + _shell_escape( FAILURE_MESSAGE + '\n\n' + message) \
+ '\\\" ' + commit + '\\\" ' + commit
commands.getstatusoutput(command) subprocess.getstatusoutput(command)
sys.exit(1) sys.exit(1)
def passes( commit ): def passes( commit ):
command = SSH_COMMAND + PASS_SCORE + ' -m \\\"' \ command = SSH_COMMAND + PASS_SCORE + ' -m \\\"' \
+ _shell_escape(PASS_MESSAGE) + ' \\\" ' + commit + _shell_escape(PASS_MESSAGE) + ' \\\" ' + commit
commands.getstatusoutput(command) subprocess.getstatusoutput(command)
def _shell_escape(x): def _shell_escape(x):
s = '' s = ''

View File

@ -36,6 +36,8 @@ Documentation is available here: https://www.codeaurora.org/xwiki/bin/QAEP/Gerri
""" """
from __future__ import print_function
import argparse import argparse
import json import json
import re import re
@ -95,7 +97,7 @@ class TrivialRebase:
try: try:
process = subprocess.Popen(command, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) process = subprocess.Popen(command, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
std_out, std_err = process.communicate() std_out, std_err = process.communicate()
except OSError, e: except OSError as e:
raise self.CheckCallError(command, cwd, e.errno, None) raise self.CheckCallError(command, cwd, e.errno, None)
if process.returncode: if process.returncode:
raise self.CheckCallError(command, cwd, process.returncode, std_out, std_err) raise self.CheckCallError(command, cwd, process.returncode, std_out, std_err)
@ -107,9 +109,9 @@ class TrivialRebase:
'--format', 'JSON', '-c', sql_query] '--format', 'JSON', '-c', sql_query]
try: try:
(gsql_out, _gsql_stderr) = self.CheckCall(gsql_cmd) (gsql_out, _gsql_stderr) = self.CheckCall(gsql_cmd)
except self.CheckCallError, e: except self.CheckCallError as e:
print "return code is %s" % e.retcode print("return code is %s" % e.retcode)
print "stdout and stderr is\n%s%s" % (e.stdout, e.stderr) print("stdout and stderr is\n%s%s" % (e.stdout, e.stderr))
raise raise
new_out = gsql_out.replace('}}\n', '}}\nsplit here\n') new_out = gsql_out.replace('}}\n', '}}\nsplit here\n')
@ -194,7 +196,7 @@ class TrivialRebase:
prev_patch_id = self.GetPatchId(prev_revision) prev_patch_id = self.GetPatchId(prev_revision)
cur_patch_id = self.GetPatchId(self.commit) cur_patch_id = self.GetPatchId(self.commit)
if prev_patch_id == '0' and cur_patch_id == '0': if prev_patch_id == '0' and cur_patch_id == '0':
print "commits %s and %s are both empty or merge commits" % (prev_revision, self.commit) print("commits %s and %s are both empty or merge commits" % (prev_revision, self.commit))
return return
if cur_patch_id != prev_patch_id: if cur_patch_id != prev_patch_id:
# patch-ids don't match # patch-ids don't match
@ -237,7 +239,7 @@ class TrivialRebase:
gerrit_review_msg = ("\'Automatically re-added by Gerrit trivial rebase " gerrit_review_msg = ("\'Automatically re-added by Gerrit trivial rebase "
"detection script.\'") "detection script.\'")
for acct, flags in self.acct_approvals.items(): for acct, flags in list(self.acct_approvals.items()):
gerrit_review_cmd = ['gerrit', 'review', '--project', self.project, gerrit_review_cmd = ['gerrit', 'review', '--project', self.project,
'--message', gerrit_review_msg, flags, self.commit] '--message', gerrit_review_msg, flags, self.commit]
email_addr = self.GetEmailFromAcctId(acct) email_addr = self.GetEmailFromAcctId(acct)
@ -246,5 +248,5 @@ class TrivialRebase:
if __name__ == "__main__": if __name__ == "__main__":
try: try:
TrivialRebase().Run() TrivialRebase().Run()
except AssertionError, e: except AssertionError as e:
print >> sys.stderr, e print(e, file=sys.stderr)

View File

@ -13,6 +13,8 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
from __future__ import print_function
from multiprocessing import cpu_count from multiprocessing import cpu_count
from os import environ, fchmod, makedirs, mkdir, path from os import environ, fchmod, makedirs, mkdir, path
from subprocess import Popen, PIPE from subprocess import Popen, PIPE
@ -31,7 +33,7 @@ for a in argv[3:]:
opt.append(a) opt.append(a)
if not outzip.endswith('.zip'): if not outzip.endswith('.zip'):
print >>stderr, "%s must end with .zip" % outzip print("%s must end with .zip" % outzip, file=stderr)
exit(1) exit(1)
rebuild = outzip[:-4] + '.rebuild' rebuild = outzip[:-4] + '.rebuild'
@ -56,13 +58,13 @@ cmd = [
gwt = Popen(cmd, stdout = PIPE, stderr = PIPE) gwt = Popen(cmd, stdout = PIPE, stderr = PIPE)
out, err = gwt.communicate() out, err = gwt.communicate()
if gwt.returncode != 0: if gwt.returncode != 0:
print >>stderr, out + err print(out + err, file=stderr)
exit(gwt.returncode) exit(gwt.returncode)
with open(rebuild, 'w') as fd: with open(rebuild, 'w') as fd:
def shquote(s): def shquote(s):
return s.replace("'", "'\\''") return s.replace("'", "'\\''")
print >>fd, '#!/bin/sh' print('#!/bin/sh', file=fd)
print >>fd, "PATH='%s'" % shquote(environ['PATH']) print("PATH='%s'" % shquote(environ['PATH']), file=fd)
print >>fd, 'buck build "$1" || exit' print('buck build "$1" || exit', file=fd)
fchmod(fd.fileno(), 0755) fchmod(fd.fileno(), 0o755)

View File

@ -13,6 +13,8 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
from __future__ import print_function
from hashlib import sha1 from hashlib import sha1
from optparse import OptionParser from optparse import OptionParser
from os import link, makedirs, path from os import link, makedirs, path
@ -64,18 +66,18 @@ if not path.exists(cache_ent):
safe_mkdirs(path.dirname(cache_ent)) safe_mkdirs(path.dirname(cache_ent))
check_call(['curl', '-sfo', cache_ent, args.u]) check_call(['curl', '-sfo', cache_ent, args.u])
except (OSError, CalledProcessError) as err: except (OSError, CalledProcessError) as err:
print >>stderr, "error using curl: %s" % str(err) print("error using curl: %s" % str(err), file=stderr)
exit(1) exit(1)
if args.v: if args.v:
have = hashfile(cache_ent) have = hashfile(cache_ent)
if args.v != have: if args.v != have:
o = cache_ent[len(root_dir) + 1:] o = cache_ent[len(root_dir) + 1:]
print >>stderr, ( print((
'%s:\n' + '%s:\n' +
'expected %s\n' + 'expected %s\n' +
'received %s\n' + 'received %s\n' +
' %s\n') % (args.u, args.v, have, o) ' %s\n') % (args.u, args.v, have, o), file=stderr)
exit(1) exit(1)
exclude = [] exclude = []
@ -91,7 +93,7 @@ if args.exclude_java_sources:
finally: finally:
zf.close() zf.close()
except (BadZipfile, LargeZipFile) as err: except (BadZipfile, LargeZipFile) as err:
print >>stderr, "error opening %s: %s" % (cache_ent, str(err)) print("error opening %s: %s" % (cache_ent, str(err)), file=stderr)
exit(1) exit(1)
safe_mkdirs(path.dirname(args.o)) safe_mkdirs(path.dirname(args.o))

View File

@ -15,6 +15,8 @@
# #
# TODO(sop): Remove hack after Buck supports Eclipse # TODO(sop): Remove hack after Buck supports Eclipse
from __future__ import print_function
from os import path, symlink from os import path, symlink
from sys import argv from sys import argv
@ -25,7 +27,7 @@ for _ in range(0, 3):
p = path.join(ROOT, '.project') p = path.join(ROOT, '.project')
with open(p, 'w') as fd: with open(p, 'w') as fd:
print >>fd, """\ print("""\
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<projectDescription> <projectDescription>
<name>gerrit</name> <name>gerrit</name>
@ -38,5 +40,5 @@ with open(p, 'w') as fd:
<nature>org.eclipse.jdt.core.javanature</nature> <nature>org.eclipse.jdt.core.javanature</nature>
</natures> </natures>
</projectDescription>\ </projectDescription>\
""" """, file=fd)
symlink(p, OUT) symlink(p, OUT)