Skip to content

Commit 43dbf46

Browse files
committed
Porting python2 to 3 modules: top level scripts 1
1 parent c7a687a commit 43dbf46

5 files changed

+61
-56
lines changed

add-externals-gh-labels.py

+11-11
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
#!/usr/bin/env python
2+
from __future__ import print_function
23
from github import Github
34
from os.path import expanduser, dirname, abspath, join
45
from githublabels import LABEL_TYPES, COMMON_LABELS, COMPARISON_LABELS, CMSSW_BUILD_LABELS, LABEL_COLORS
5-
from categories import COMMON_CATEGORIES, EXTERNAL_CATEGORIES, EXTERNAL_REPOS, CMSSW_REPOS, CMSDIST_REPOS, CMSSW_CATEGORIES
6+
from categories import COMMON_CATEGORIES, EXTERNAL_CATEGORIES, EXTERNAL_REPOS, CMSSW_REPOS, CMSSW_CATEGORIES
67
from cms_static import VALID_CMS_SW_REPOS_FOR_TESTS, GH_CMSSW_ORGANIZATION
7-
from datetime import datetime
88
from socket import setdefaulttimeout
9-
from github_utils import api_rate_limits, api_rate_limits_repo
9+
from github_utils import api_rate_limits
1010
from cmsutils import get_config_map_properties
1111
from sys import argv
1212
setdefaulttimeout(120)
@@ -24,29 +24,29 @@ def setRepoLabels (gh, repo_name, all_labels, dryRun=False, ignore=[]):
2424
if repo.name not in VALID_CMS_SW_REPOS_FOR_TESTS:
2525
skip = True
2626
if skip:
27-
print "Ignoring repo:",repo.full_name
27+
print("Ignoring repo:",repo.full_name)
2828
continue
2929
repos.append(repo)
3030
else:
3131
repos.append(gh.get_repo(repo_name))
3232
api_rate_limits(gh)
3333
for repo in repos:
34-
print "Checking repository ", repo.full_name, ", DryRun:",dryRun
34+
print("Checking repository ", repo.full_name, ", DryRun:",dryRun)
3535
cur_labels = {}
3636
for lab in repo.get_labels():
3737
cur_labels [lab.name]=lab
3838
api_rate_limits(gh)
3939
for lab in all_labels:
4040
if not lab in cur_labels:
41-
print " Creating new label ",lab,"=>",all_labels[lab]
41+
print(" Creating new label ",lab,"=>",all_labels[lab])
4242
if not dryRun:
4343
repo.create_label(lab, all_labels[lab])
4444
api_rate_limits(gh)
4545
elif cur_labels[lab].color != all_labels[lab]:
4646
if not dryRun:
4747
cur_labels[lab].edit(lab, all_labels[lab])
4848
api_rate_limits(gh)
49-
print " Label ",lab," color updated: ",cur_labels[lab].color ," => ",all_labels[lab]
49+
print(" Label ",lab," color updated: ",cur_labels[lab].color ," => ",all_labels[lab])
5050

5151
if __name__ == "__main__":
5252
from optparse import OptionParser
@@ -70,7 +70,7 @@ def setRepoLabels (gh, repo_name, all_labels, dryRun=False, ignore=[]):
7070

7171
if opts.cmssw or opts.externals:
7272
all_labels = COMMON_LABELS
73-
for cat in COMMON_CATEGORIES+EXTERNAL_CATEGORIES+CMSSW_CATEGORIES.keys():
73+
for cat in COMMON_CATEGORIES+EXTERNAL_CATEGORIES+list(CMSSW_CATEGORIES.keys()):
7474
for lab in LABEL_TYPES:
7575
all_labels[cat+"-"+lab]=LABEL_TYPES[lab]
7676
for lab in COMPARISON_LABELS:
@@ -101,14 +101,14 @@ def setRepoLabels (gh, repo_name, all_labels, dryRun=False, ignore=[]):
101101
from glob import glob
102102
for rconf in glob(join(SCRIPT_DIR,"repos","*","*","repo_config.py")):
103103
repo_data = rconf.split("/")[-4:-1]
104-
exec 'from '+".".join(repo_data)+' import categories, repo_config'
105-
print repo_config.GH_TOKEN, repo_config.GH_REPO_FULLNAME
104+
exec('from '+".".join(repo_data)+' import categories, repo_config')
105+
print(repo_config.GH_TOKEN, repo_config.GH_REPO_FULLNAME)
106106
if not repo_config.ADD_LABELS: continue
107107
gh = Github(login_or_token=open(expanduser(repo_config.GH_TOKEN)).read().strip())
108108
all_labels = COMMON_LABELS
109109
for lab in COMPARISON_LABELS:
110110
all_labels[lab] = COMPARISON_LABELS[lab]
111-
for cat in categories.COMMON_CATEGORIES+categories.CMSSW_CATEGORIES.keys():
111+
for cat in categories.COMMON_CATEGORIES+list(categories.CMSSW_CATEGORIES.keys()):
112112
for lab in LABEL_TYPES:
113113
all_labels[cat+"-"+lab]=LABEL_TYPES[lab]
114114
setRepoLabels (gh, repo_config.GH_REPO_FULLNAME, all_labels, opts.dryRun)

auto-create-pull-requests

+7-6
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
#!/usr/bin/env python
22
# Creates pull requests to automatically forward port from one release to another.
3+
from __future__ import print_function
34
from github import Github, GithubException
45
from sys import exit
56
from os.path import expanduser
@@ -31,7 +32,7 @@ if __name__ == "__main__":
3132
try:
3233
gh_repo = gh.get_organization("cms-sw").get_repo(repo)
3334
except:
34-
print "Could not find repository."
35+
print("Could not find repository.")
3536
exit(0)
3637
for (head, base) in MAPPINGS[repo]:
3738
title = "Forward port %s into %s" % (head, base)
@@ -41,13 +42,13 @@ if __name__ == "__main__":
4142
body="",
4243
base=base,
4344
head=head)
44-
except GithubException, e:
45+
except GithubException as e:
4546
if e.data[u"errors"][0][u"message"].startswith("No commits between"):
46-
print "%s already in %s" % (head, base)
47+
print("%s already in %s" % (head, base))
4748
elif e.data[u"errors"][0][u"message"].startswith("A pull request already exists"):
48-
print "%s is already pending for merge in %s" % (head, base)
49+
print("%s is already pending for merge in %s" % (head, base))
4950
else:
50-
print e.data
51+
print(e.data)
5152
exit(1)
5253
if pr:
53-
print pr
54+
print(pr)

backport-pr.py

+10-9
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,40 @@
11
#!/usr/bin/env python
2+
from __future__ import print_function
23
from github import Github, GithubException
34
from sys import exit
45
from os.path import expanduser
56
from argparse import ArgumentParser
67
from cms_static import GH_CMSSW_ORGANIZATION
78
from cms_static import GH_CMSSW_REPO
8-
from commands import getstatusoutput as run_cmd
9+
from _py2with3compatibility import run_cmd
910
CMSSW_GIT_REF="/cvmfs/cms.cern.ch/cmssw.git.daily"
1011

1112
def backport_pull (repo, pr, branch):
1213
pr_branch = pr.base.label.split(":")[1]
13-
print "Source Branch:",pr_branch
14+
print("Source Branch:",pr_branch)
1415
if pr_branch == branch: return "Warning: Can not backport, same branch %s vs %s" % (pr_branch, branch),False
1516
br = gh_repo.get_branch(branch)
1617
commits = []
1718
for c in pr.get_commits().reversed: commits.insert(0,"git cherry-pick %s" % c.sha)
1819
if not commits: return "There are no commits to backport",False
19-
print "Cherry-pick commands:"
20-
print " "+"\n ".join(commits)
20+
print("Cherry-pick commands:")
21+
print(" "+"\n ".join(commits))
2122
if len(commits)>=250:
2223
return "Error: Too many commits in PR %s\nBot can only handle max 250 commits." % len(commits),False
2324
new_branch = "backport-%s-%s" % (branch.replace("/","_"), pr.number)
24-
print "New Branch:",new_branch
25+
print("New Branch:",new_branch)
2526
git_ref = ""
2627
if repo.name == "cmssw": git_ref = "--reference "+CMSSW_GIT_REF
27-
print "GIT REF:",git_ref
28+
print("GIT REF:",git_ref)
2829
e , o = run_cmd("rm -rf pr_backport; git clone --branch %s %s [email protected]:%s pr_backport && cd pr_backport && git checkout -b %s" % (branch, git_ref, repo.full_name, new_branch))
2930
if e:
30-
print o
31+
print(o)
3132
exit(1)
3233
e, o = run_cmd('cd pr_backport; %s' % ";".join(commits))
3334
if e: return "Error: Failed to cherry-pick commits. Please backport this PR yourself.\n```"+o+"\n```",False
3435
e, o = run_cmd("cd pr_backport; git push origin %s" % new_branch)
3536
if e:
36-
print o
37+
print(o)
3738
exit(1)
3839
run_cmd("rm -rf pr_backport")
3940
newBody = "backport of #%s\n\n%s" %(pr.number, pr.body)
@@ -56,5 +57,5 @@ def backport_pull (repo, pr, branch):
5657
res = backport_pull (gh_repo, pr, args.branch)
5758
status = "done"
5859
if not res[1]: status = "failed\n**Reason:**\n"
59-
print res
60+
print(res)
6061
pr.create_issue_comment("backport %s\n%s" % (status, res[0]))

build-node-stats

+14-13
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
#!/usr/bin/env python
2+
from __future__ import print_function
23
import sys
3-
sys.exit(0)
4+
sys.exit(0) # TODO script not run anymore?
45

5-
from commands import getstatusoutput
6+
from _py2with3compatibility import run_cmd
67
from socket import gethostname
78
from argparse import ArgumentParser
89
import time
@@ -11,7 +12,7 @@ import struct
1112
import socket
1213

1314
def chunks(l, n):
14-
for i in xrange(0, len(l), n):
15+
for i in range(0, len(l), n):
1516
yield l[i:i+n]
1617

1718
def format(s, **kwds):
@@ -24,25 +25,25 @@ CARBON_PORT=2004
2425
def sendMetrics(metrics):
2526
for l in chunks(metrics, 100):
2627
payload = pickle.dumps(l)
27-
print len(payload)
28+
print(len(payload))
2829
header = struct.pack("!L", len(payload))
2930
message = header + payload
3031
sock = socket.socket()
31-
print CARBON_SERVER, CARBON_PORT
32+
print(CARBON_SERVER, CARBON_PORT)
3233
sock.connect((CARBON_SERVER, CARBON_PORT))
3334
sock.sendall(message)
3435
sock.close()
3536

3637
def aggregate(metrics):
3738
aggregated = {}
3839
for x in metrics:
39-
print x[0]
40-
if x[0] in aggregated.keys():
40+
print(x[0])
41+
if x[0] in list(aggregated.keys()):
4142
aggregated[x[0]][1][1] += x[1][1]
42-
print x[0],"now", aggregated[x[0]][1][1]
43+
print(x[0],"now", aggregated[x[0]][1][1])
4344
else:
4445
aggregated[x[0]] = x
45-
return [x for x in aggregated.values()]
46+
return [x for x in list(aggregated.values())]
4647

4748
if __name__ == "__main__":
4849
parser = ArgumentParser()
@@ -56,15 +57,15 @@ if __name__ == "__main__":
5657

5758
fields = ("pid", "comm", "pcpu", "rss", "vsize")
5859
cmd = 'ps -U cmsbuild -o %s= -o %s= -o %s= -o %s= -o %s=' % fields
59-
err, out = getstatusoutput(cmd)
60+
err, out = run_cmd(cmd)
6061
if err:
61-
print "Error while reading process data"
62+
print("Error while reading process data")
6263
exit(1)
63-
print out
64+
print(out)
6465
metrics = []
6566
timestamp = time.time()
6667
for l in out.split("\n"):
67-
data = dict(zip(fields, [x for x in l.split(" ") if x]))
68+
data = dict(list(zip(fields, [x for x in l.split(" ") if x])))
6869
try:
6970
data["pid"] = int(data["pid"])
7071
data["pcpu"] = float(data["pcpu"])

buildLogAnalyzer.py

+19-17
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,12 @@
66
Created by Andreas Pfeiffer on 2008-08-05.
77
Copyright (c) 2008 CERN. All rights reserved.
88
"""
9-
9+
from __future__ import print_function
10+
from past.builtins import cmp
1011
import sys, os, re, time
1112
import getopt
1213

14+
1315
def pkgCmp(a,b):
1416
if a.subsys == b.subsys: return cmp(a.pkg, b.pkg)
1517
else: return cmp(a.subsys, b.subsys)
@@ -65,7 +67,7 @@ def __init__(self, topDirIn='.', topUrlIn='', verbose = -1, pkgsList = None, rel
6567
if not pkgsList: pkgsList = "../../../../../src/PackageList.cmssw"
6668
if self.topURL != '' :
6769
if self.topURL[-1] != '/' : self.topURL += '/'
68-
if not release: release = self.topURL.split('/')[-3]
70+
if not release: release = self.topURL.split('/')[-3] # TODO no error catching
6971
self.release = release
7072
self.pkgsList = pkgsList
7173
self.verbose = verbose
@@ -138,7 +140,7 @@ def analyze(self):
138140
start = time.time()
139141
packageList = glob.glob('*/*/build.log')
140142

141-
if self.verbose > 0: print "going to analyze ", len(packageList), 'files.'
143+
if self.verbose > 0: print("going to analyze ", len(packageList), 'files.')
142144

143145
for logFile in packageList:
144146
self.analyzeFile(logFile)
@@ -151,7 +153,7 @@ def analyze(self):
151153
for key in self.errorKeys:
152154
if key in pkg.errSummary.keys() :
153155
self.errMapAll[key].append(pkg)
154-
if key in pkg.errSummary.keys() and pkg not in pkgDone:
156+
if key in pkg.errSummary.keys() and pkg not in pkgDone:
155157
self.errMap[key].append(pkg)
156158
pkgDone.append(pkg)
157159
else:
@@ -164,17 +166,17 @@ def analyze(self):
164166
def report(self):
165167
"""show collected info"""
166168

167-
print 'analyzed ', len(self.packageList), 'log files in', str(self.anaTime), 'sec.'
169+
print('analyzed ', len(self.packageList), 'log files in', str(self.anaTime), 'sec.')
168170
totErr = 0
169171
for key, val in self.nErrorInfo.items():
170172
totErr += int(val)
171173

172-
print 'found ', totErr, ' errors and warnings in total, by type:'
174+
print('found ', totErr, ' errors and warnings in total, by type:')
173175
for key, val in self.nErrorInfo.items():
174-
print '\t', key, ' : ', val, ' in ', len(self.errMapAll[key]), 'packages'
176+
print('\t', key, ' : ', val, ' in ', len(self.errMapAll[key]), 'packages')
175177

176-
print 'found ', len(self.pkgOK), 'packages without errors/warnings.'
177-
print 'found ', len(self.pkgErr), 'packages with errors or warnings, ', len(self.pkgWarn), ' with warnings only.'
178+
print('found ', len(self.pkgOK), 'packages without errors/warnings.')
179+
print('found ', len(self.pkgErr), 'packages with errors or warnings, ', len(self.pkgWarn), ' with warnings only.')
178180
# for pkg in pkgErr:
179181
# print '\t',pkg.name(), ' : ',
180182
# for key in ['dictError', 'compError', 'linkError']:
@@ -201,7 +203,7 @@ def report(self):
201203
for pkg in self.pkgOK:
202204
self.makeHTMLLogFile(pkg)
203205
stop = time.time()
204-
print "creating html pages took ", str(stop-start), 'sec.'
206+
print("creating html pages took ", str(stop-start), 'sec.')
205207

206208
def makeHTMLSummaryPage(self):
207209

@@ -356,10 +358,9 @@ def analyzeFile(self, fileNameIn):
356358
"""read in file and check for errors"""
357359
subsys, pkg, logFile = fileNameIn.split('/')
358360

359-
if self.verbose > 5 : print "analyzing file : ", fileNameIn
361+
if self.verbose > 5 : print("analyzing file : ", fileNameIn)
360362

361363
fileIn = open(fileNameIn, 'r')
362-
lines = fileIn.xreadlines()
363364
shLib = 'so'
364365
if os.uname()[0] == 'Darwin' :
365366
shLib = 'dylib'
@@ -414,7 +415,7 @@ def analyzeFile(self, fileNameIn):
414415

415416
pkgInfo = PackageInfo(subsys, pkg)
416417
lineNo = -1
417-
for line in lines:
418+
for line in fileIn:
418419
lineNo += 1
419420
errFound = False
420421
for errI in errors:
@@ -488,7 +489,7 @@ def main(argv=None):
488489
try:
489490
try:
490491
opts, args = getopt.getopt(argv[1:], "hv:l:t:p:r:", ["help", "verbose=", "logDir=", "topURL=", "pkgList=", "release="])
491-
except getopt.error, msg:
492+
except getopt.error as msg:
492493
raise Usage(msg)
493494

494495
# option processing
@@ -515,10 +516,11 @@ def main(argv=None):
515516
lfa.analyze()
516517
lfa.report()
517518

518-
except Usage, err:
519-
print >> sys.stderr, sys.argv[0].split("/")[-1] + ": " + str(err.msg)
520-
print >> sys.stderr, "\t for help use --help"
519+
except Usage as err:
520+
print(sys.argv[0].split("/")[-1] + ": " + str(err.msg), file=sys.stderr)
521+
print("\t for help use --help", file=sys.stderr)
521522
return 2
522523

524+
523525
if __name__ == "__main__":
524526
sys.exit(main(sys.argv))

0 commit comments

Comments
 (0)