Python cleanups, round 1: whitespace

- Use 4 spaces instead of 2 for indentation. This is Python standard
  and is also in Google's styleguide for Python:
  https://google.github.io/styleguide/pyguide.html#Indentation
- Use 2 newlines between functions/classes

This does introduce a few line-too-long errors to clean up which will
be fixed in the follow-up commit, but wanted to keep this as easy to
review as possible (git diff -w should be minimal)

Change-Id: I463f18d11e72745107350ac0ae5588d1fb626ed6
This commit is contained in:
Chad Horohoe
2018-05-16 22:33:06 -04:00
committed by Paladox
parent c1399cf4c7
commit dd22470db8
19 changed files with 1217 additions and 1152 deletions

View File

@@ -17,6 +17,7 @@ FAILURE_MESSAGE = 'This commit message does not match the standard.' \
PASS_SCORE = '--code-review=0' PASS_SCORE = '--code-review=0'
PASS_MESSAGE = '' PASS_MESSAGE = ''
def main(): def main():
change = None change = None
project = None project = None
@@ -76,11 +77,13 @@ 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) \
@@ -88,11 +91,13 @@ def fail( commit, message ):
subprocess.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
subprocess.getstatusoutput(command) subprocess.getstatusoutput(command)
def _shell_escape(x): def _shell_escape(x):
s = '' s = ''
for c in x: for c in x:
@@ -102,6 +107,6 @@ def _shell_escape(x):
s = s + c s = s + c
return s return s
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@@ -269,6 +269,7 @@ def clean_up():
def main(): def main():
<<<<<<< HEAD
p = optparse.OptionParser() p = optparse.OptionParser()
p.add_option("-u", "--user_count", action="store", p.add_option("-u", "--user_count", action="store",
default=100, default=100,
@@ -301,5 +302,40 @@ def main():
for idx, u in enumerate(gerrit_users): for idx, u in enumerate(gerrit_users):
for _ in range(random.randint(1, 5)): for _ in range(random.randint(1, 5)):
create_change(u, project_names[4 * idx / len(gerrit_users)]) create_change(u, project_names[4 * idx / len(gerrit_users)])
=======
p = optparse.OptionParser()
p.add_option("-u", "--user_count", action="store",
default=100,
type='int',
help="number of users to generate")
p.add_option("-p", "--port", action="store",
default=8080,
type='int',
help="port of server")
(options, _) = p.parse_args()
global BASE_URL
BASE_URL = BASE_URL % options.port
print(BASE_URL)
set_up()
gerrit_users = get_random_users(options.user_count)
group_names = create_gerrit_groups()
for idx, u in enumerate(gerrit_users):
u["groups"].append(group_names[idx % len(group_names)])
if idx % 5 == 0:
# Also add to security group
u["groups"].append(group_names[4])
generate_ssh_keys(gerrit_users)
create_gerrit_users(gerrit_users)
project_names = create_gerrit_projects(group_names)
for idx, u in enumerate(gerrit_users):
for _ in xrange(random.randint(1, 5)):
create_change(u, project_names[4 * idx / len(gerrit_users)])
>>>>>>> 730efd14f4... Python cleanups, round 1: whitespace
main() main()

View File

@@ -10,12 +10,14 @@ fnCompiledRegex = re.compile(removeSelfInvokeRegex, re.DOTALL)
regexBehavior = r"<script>(.+)<\/script>" regexBehavior = r"<script>(.+)<\/script>"
behaviorCompiledRegex = re.compile(regexBehavior, re.DOTALL) behaviorCompiledRegex = re.compile(regexBehavior, re.DOTALL)
def _open(filename, mode="r"): def _open(filename, mode="r"):
try: try:
return open(filename, mode, encoding="utf-8") return open(filename, mode, encoding="utf-8")
except TypeError: except TypeError:
return open(filename, mode) return open(filename, mode)
def replaceBehaviorLikeHTML(fileIn, fileOut): def replaceBehaviorLikeHTML(fileIn, fileOut):
with _open(fileIn) as f: with _open(fileIn) as f:
file_str = f.read() file_str = f.read()
@@ -24,16 +26,19 @@ def replaceBehaviorLikeHTML (fileIn, fileOut):
with _open("polygerrit-ui/temp/behaviors/" + fileOut.replace("html", "js"), "w+") as f: with _open("polygerrit-ui/temp/behaviors/" + fileOut.replace("html", "js"), "w+") as f:
f.write(match.group(1)) f.write(match.group(1))
def replaceBehaviorLikeJS(fileIn, fileOut): def replaceBehaviorLikeJS(fileIn, fileOut):
with _open(fileIn) as f: with _open(fileIn) as f:
file_str = f.read() file_str = f.read()
with _open("polygerrit-ui/temp/behaviors/" + fileOut, "w+") as f: with _open("polygerrit-ui/temp/behaviors/" + fileOut, "w+") as f:
f.write(file_str) f.write(file_str)
def generateStubBehavior(behaviorName): def generateStubBehavior(behaviorName):
with _open("polygerrit-ui/temp/behaviors/" + behaviorName + ".js", "w+") as f: with _open("polygerrit-ui/temp/behaviors/" + behaviorName + ".js", "w+") as f:
f.write("/** @polymerBehavior **/\n" + behaviorName + "= {};") f.write("/** @polymerBehavior **/\n" + behaviorName + "= {};")
def replacePolymerElement(fileIn, fileOut, root): def replacePolymerElement(fileIn, fileOut, root):
with _open(fileIn) as f: with _open(fileIn) as f:
key = fileOut.split('.')[0] key = fileOut.split('.')[0]
@@ -56,6 +61,7 @@ def replacePolymerElement (fileIn, fileOut, root):
elements[key]["js"] = "polygerrit-ui/temp/" + fileOut elements[key]["js"] = "polygerrit-ui/temp/" + fileOut
elements[key]["package"] = package elements[key]["package"] = package
def writeTempFile(file, root): def writeTempFile(file, root):
# This is included in an extern because it is directly on the window object. # This is included in an extern because it is directly on the window object.
# (for now at least). # (for now at least).

View File

@@ -19,6 +19,7 @@
from __future__ import print_function from __future__ import print_function
import sys import sys
def print_help(): def print_help():
for (n, v) in vars(sys.modules['__main__']).items(): for (n, v) in vars(sys.modules['__main__']).items():
if not n.startswith("__") and not n in ['help', 'reload'] \ if not n.startswith("__") and not n in ['help', 'reload'] \
@@ -29,4 +30,5 @@ def print_help():
print("Welcome to the Gerrit Inspector") print("Welcome to the Gerrit Inspector")
print("Enter help() to see the above again, EOF to quit and stop Gerrit") print("Enter help() to see the above again, EOF to quit and stop Gerrit")
print_help() print_help()

View File

@@ -74,6 +74,7 @@ def cache_entry(args):
name = '%s-%s' % (path.basename(args.o), h) name = '%s-%s' % (path.basename(args.o), h)
return path.join(CACHE_DIR, name) return path.join(CACHE_DIR, name)
opts = OptionParser() opts = OptionParser()
opts.add_option('-o', help='local output file') opts.add_option('-o', help='local output file')
opts.add_option('-u', help='URL to download') opts.add_option('-u', help='URL to download')

View File

@@ -56,6 +56,7 @@ args, _ = opts.parse_args()
batch_option = '--batch' if args.batch else None batch_option = '--batch' if args.batch else None
def _build_bazel_cmd(*args): def _build_bazel_cmd(*args):
cmd = ['bazel'] cmd = ['bazel']
if batch_option: if batch_option:
@@ -64,15 +65,18 @@ def _build_bazel_cmd(*args):
cmd.append(arg) cmd.append(arg)
return cmd return cmd
def retrieve_ext_location(): def retrieve_ext_location():
return check_output(_build_bazel_cmd('info', 'output_base')).strip() return check_output(_build_bazel_cmd('info', 'output_base')).strip()
def gen_bazel_path(): def gen_bazel_path():
bazel = check_output(['which', 'bazel']).strip().decode('UTF-8') bazel = check_output(['which', 'bazel']).strip().decode('UTF-8')
with open(path.join(ROOT, ".bazel_path"), 'w') as fd: with open(path.join(ROOT, ".bazel_path"), 'w') as fd:
fd.write("bazel=%s\n" % bazel) fd.write("bazel=%s\n" % bazel)
fd.write("PATH=%s\n" % environ["PATH"]) fd.write("PATH=%s\n" % environ["PATH"])
def _query_classpath(target): def _query_classpath(target):
deps = [] deps = []
t = cp_targets[target] t = cp_targets[target]
@@ -84,6 +88,7 @@ def _query_classpath(target):
deps = [line.rstrip('\n') for line in open(name)] deps = [line.rstrip('\n') for line in open(name)]
return deps return deps
def gen_project(name='gerrit', root=ROOT): def gen_project(name='gerrit', root=ROOT):
p = path.join(root, '.project') p = path.join(root, '.project')
with open(p, 'w') as fd: with open(p, 'w') as fd:
@@ -102,6 +107,7 @@ def gen_project(name='gerrit', root=ROOT):
</projectDescription>\ </projectDescription>\
""" % {"name": name}, file=fd) """ % {"name": name}, file=fd)
def gen_plugin_classpath(root): def gen_plugin_classpath(root):
p = path.join(root, '.classpath') p = path.join(root, '.classpath')
with open(p, 'w') as fd: with open(p, 'w') as fd:
@@ -120,6 +126,7 @@ def gen_plugin_classpath(root):
<classpathentry kind="output" path="eclipse-out/classes"/> <classpathentry kind="output" path="eclipse-out/classes"/>
</classpath>""" % {"testpath": testpath}, file=fd) </classpath>""" % {"testpath": testpath}, file=fd)
def gen_classpath(ext): def gen_classpath(ext):
def make_classpath(): def make_classpath():
impl = minidom.getDOMImplementation() impl = minidom.getDOMImplementation()
@@ -270,6 +277,7 @@ def gen_classpath(ext):
print('error generating project for %s: %s' % (plugin, err), print('error generating project for %s: %s' % (plugin, err),
file=sys.stderr) file=sys.stderr)
def gen_factorypath(ext): def gen_factorypath(ext):
doc = minidom.getDOMImplementation().createDocument(None, 'factorypath', None) doc = minidom.getDOMImplementation().createDocument(None, 'factorypath', None)
for jar in _query_classpath(AUTO): for jar in _query_classpath(AUTO):
@@ -284,6 +292,7 @@ def gen_factorypath(ext):
with open(p, 'w') as fd: with open(p, 'w') as fd:
doc.writexml(fd, addindent='\t', newl='\n', encoding='UTF-8') doc.writexml(fd, addindent='\t', newl='\n', encoding='UTF-8')
try: try:
ext_location = retrieve_ext_location().decode("utf-8") ext_location = retrieve_ext_location().decode("utf-8")
gen_project(args.project_name) gen_project(args.project_name)

View File

@@ -118,12 +118,14 @@ def build_bower_json(version_targets, seeds):
json.dump(bower_json, f, indent=2) json.dump(bower_json, f, indent=2)
return ret return ret
def decode(input): def decode(input):
try: try:
return input.decode("utf-8") return input.decode("utf-8")
except TypeError: except TypeError:
return input return input
def bower_command(args): def bower_command(args):
base = subprocess.check_output(["bazel", "info", "output_base"]).strip() base = subprocess.check_output(["bazel", "info", "output_base"]).strip()
exp = os.path.join(decode(base), "external", "bower", "*npm_binary.tgz") exp = os.path.join(decode(base), "external", "bower", "*npm_binary.tgz")

View File

@@ -33,6 +33,7 @@ def extract(path, outdir, bin):
# Use a temp directory adjacent to outdir so shutil.move can use the same # Use a temp directory adjacent to outdir so shutil.move can use the same
# device atomically. # device atomically.
tmpdir = tempfile.mkdtemp(dir=os.path.dirname(outdir)) tmpdir = tempfile.mkdtemp(dir=os.path.dirname(outdir))
def cleanup(): def cleanup():
try: try:
shutil.rmtree(tmpdir) shutil.rmtree(tmpdir)
@@ -57,6 +58,7 @@ def extract(path, outdir, bin):
# finished. # finished.
extract_one(tar.getmember(bin)) extract_one(tar.getmember(bin))
def main(args): def main(args):
path = args[0] path = args[0]
suffix = '.npm_binary.tgz' suffix = '.npm_binary.tgz'

View File

@@ -16,6 +16,7 @@
import unittest import unittest
from util import resolve_url from util import resolve_url
class TestResolveUrl(unittest.TestCase): class TestResolveUrl(unittest.TestCase):
""" run to test: """ run to test:
python -m unittest -v util_test python -m unittest -v util_test
@@ -39,5 +40,6 @@ class TestResolveUrl(unittest.TestCase):
{'MAVEN_EXAMPLE': 'http://maven.example.com/release'}) {'MAVEN_EXAMPLE': 'http://maven.example.com/release'})
self.assertEqual(url, 'http://maven.example.com/release/foo.jar') self.assertEqual(url, 'http://maven.example.com/release/foo.jar')
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()