Add gerritx project infrastructure.

Add all of the support files needed for this to be a project.
Also, fix pep8 and pyflakes errors.
diff --git a/gerritx/cmd/__init__.py b/gerritx/cmd/__init__.py
new file mode 100644
index 0000000..150f9ad
--- /dev/null
+++ b/gerritx/cmd/__init__.py
@@ -0,0 +1,13 @@
+# Copyright (c) 2012 Hewlett-Packard Development Company, L.P.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations
+# under the License.
diff --git a/gerritx/cmd/close_pull_requests.py b/gerritx/cmd/close_pull_requests.py
old mode 100755
new mode 100644
index cecbd32..e7742f1
--- a/gerritx/cmd/close_pull_requests.py
+++ b/gerritx/cmd/close_pull_requests.py
@@ -44,51 +44,59 @@
 import yaml
 import logging
 
-logging.basicConfig(level=logging.ERROR)
-
-PROJECTS_YAML = os.environ.get('PROJECTS_YAML',
-                               '/home/gerrit2/projects.yaml')
-GITHUB_SECURE_CONFIG = os.environ.get('GITHUB_SECURE_CONFIG',
-                                      '/etc/github/github.secure.config')
-
 MESSAGE = """Thank you for contributing to OpenStack!
 
 %(project)s uses Gerrit for code review.
 
-Please visit http://wiki.openstack.org/GerritWorkflow and follow the instructions there to upload your change to Gerrit.
+Please visit http://wiki.openstack.org/GerritWorkflow and follow the
+instructions there to upload your change to Gerrit.
 """
 
-secure_config = ConfigParser.ConfigParser()
-secure_config.read(GITHUB_SECURE_CONFIG)
-(defaults, config) = [config for config in yaml.load_all(open(PROJECTS_YAML))]
 
-if secure_config.has_option("github", "oauth_token"):
-    ghub = github.Github(secure_config.get("github", "oauth_token"))
-else:
-    ghub = github.Github(secure_config.get("github", "username"),
-                         secure_config.get("github", "password"))
+def main():
 
-orgs = ghub.get_user().get_orgs()
-orgs_dict = dict(zip([o.login.lower() for o in orgs], orgs))
-for section in config:
-    project = section['project']
+    logging.basicConfig(level=logging.ERROR)
 
-    # Make sure we're supposed to close pull requests for this project:
-    if 'options' in section and 'has-pull-requests' in section['options']:
-        continue
+    PROJECTS_YAML = os.environ.get('PROJECTS_YAML',
+                                   '/home/gerrit2/projects.yaml')
+    GITHUB_SECURE_CONFIG = os.environ.get('GITHUB_SECURE_CONFIG',
+                                          '/etc/github/github.secure.config')
 
-    # Find the project's repo
-    project_split = project.split('/', 1)
-    if len(project_split) > 1:
-        repo = orgs_dict[project_split[0].lower()].get_repo(project_split[1])
+    secure_config = ConfigParser.ConfigParser()
+    secure_config.read(GITHUB_SECURE_CONFIG)
+    (defaults, config) = [config for config in
+                          yaml.load_all(open(PROJECTS_YAML))]
+
+    if secure_config.has_option("github", "oauth_token"):
+        ghub = github.Github(secure_config.get("github", "oauth_token"))
     else:
-        repo = ghub.get_user().get_repo(project)
+        ghub = github.Github(secure_config.get("github", "username"),
+                             secure_config.get("github", "password"))
 
-    # Close each pull request
-    pull_requests = repo.get_pulls("open")
-    for req in pull_requests:
-        vars = dict(project=project)
-        issue_data = {"url": repo.url + "/issues/" + str(req.number)}
-        issue = github.Issue.Issue(req._requester, issue_data, completed = True)
-        issue.create_comment(MESSAGE % vars)
-        req.edit(state = "closed")
+    orgs = ghub.get_user().get_orgs()
+    orgs_dict = dict(zip([o.login.lower() for o in orgs], orgs))
+    for section in config:
+        project = section['project']
+
+        # Make sure we're supposed to close pull requests for this project:
+        if 'options' in section and 'has-pull-requests' in section['options']:
+            continue
+
+        # Find the project's repo
+        project_split = project.split('/', 1)
+        if len(project_split) > 1:
+            org = orgs_dict[project_split[0].lower()]
+            repo = org.get_repo(project_split[1])
+        else:
+            repo = ghub.get_user().get_repo(project)
+
+        # Close each pull request
+        pull_requests = repo.get_pulls("open")
+        for req in pull_requests:
+            vars = dict(project=project)
+            issue_data = {"url": repo.url + "/issues/" + str(req.number)}
+            issue = github.Issue.Issue(req._requester,
+                                       issue_data,
+                                       completed=True)
+            issue.create_comment(MESSAGE % vars)
+            req.edit(state="closed")
diff --git a/gerritx/cmd/expire_old_reviews.py b/gerritx/cmd/expire_old_reviews.py
index f9e908a..b542123 100644
--- a/gerritx/cmd/expire_old_reviews.py
+++ b/gerritx/cmd/expire_old_reviews.py
@@ -23,56 +23,82 @@
 import logging
 import argparse
 
-parser = argparse.ArgumentParser()
-parser.add_argument('user', help='The gerrit admin user')
-parser.add_argument('ssh_key', help='The gerrit admin SSH key file')
-options = parser.parse_args()
-
-GERRIT_USER = options.user
-GERRIT_SSH_KEY = options.ssh_key
-
-logging.basicConfig(format='%(asctime)-6s: %(name)s - %(levelname)s - %(message)s', filename='/var/log/gerrit/expire_reviews.log')
-logger= logging.getLogger('expire_reviews')
+logger = logging.getLogger('expire_reviews')
 logger.setLevel(logging.INFO)
 
-logger.info('Starting expire reviews')
-logger.info('Connecting to Gerrit')
 
-ssh = paramiko.SSHClient()
-ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
-ssh.connect('localhost', username=GERRIT_USER, key_filename=GERRIT_SSH_KEY, port=29418)
+def expire_patch_set(ssh, patch_id, patch_subject, has_negative):
+    if has_negative:
+        message = ('code review expired after 1 week of no activity'
+                   ' after a negative review, it can be restored using'
+                   ' the \`Restore Change\` button under the Patch Set'
+                   ' on the web interface')
+    else:
+        message = ('code review expired after 2 weeks of no activity,'
+                   ' it can be restored using the \`Restore Change\` button '
+                   ' under the Patch Set on the web interface')
+    command = ('gerrit review --abandon'
+               '--message="{message}" {patch_id}').format(
+                   message=message,
+                   patch_id=patch_id)
 
-def expire_patch_set(patch_id, patch_subject, has_negative):
-  if has_negative:
-    message= 'code review expired after 1 week of no activity after a negative review, it can be restored using the \`Restore Change\` button under the Patch Set on the web interface'
-  else:
-    message= 'code review expired after 2 weeks of no activity, it can be restored using the \`Restore Change\` button under the Patch Set on the web interface'
-  command='gerrit review --abandon --message="{0}" {1}'.format(message, patch_id)
-  logger.info('Expiring: %s - %s: %s', patch_id, patch_subject, message)
-  stdin, stdout, stderr = ssh.exec_command(command)
-  if stdout.channel.recv_exit_status() != 0:
-    logger.error(stderr.read())
+    logger.info('Expiring: %s - %s: %s', patch_id, patch_subject, message)
+    stdin, stdout, stderr = ssh.exec_command(command)
+    if stdout.channel.recv_exit_status() != 0:
+        logger.error(stderr.read())
 
-# Query all open with no activity for 2 weeks
-logger.info('Searching no activity for 2 weeks')
-stdin, stdout, stderr = ssh.exec_command('gerrit query --current-patch-set --format JSON status:open age:2w')
 
-for line in stdout:
-  row= json.loads(line)
-  if not row.has_key('rowCount'):
-    expire_patch_set(row['currentPatchSet']['revision'], row['subject'], False)
+def main():
 
-# Query all reviewed with no activity for 1 week
-logger.info('Searching no activity on negative review for 1 week')
-stdin, stdout, stderr = ssh.exec_command('gerrit query --current-patch-set --all-approvals --format JSON status:reviewed age:1w')
+    parser = argparse.ArgumentParser()
+    parser.add_argument('user', help='The gerrit admin user')
+    parser.add_argument('ssh_key', help='The gerrit admin SSH key file')
+    options = parser.parse_args()
 
-for line in stdout:
-  row= json.loads(line)
-  if not row.has_key('rowCount'):
-    # Search for negative approvals
-    for approval in row['currentPatchSet']['approvals']:
-      if approval['value'] == '-1':
-        expire_patch_set(row['currentPatchSet']['revision'], row['subject'], True)
-        break
+    GERRIT_USER = options.user
+    GERRIT_SSH_KEY = options.ssh_key
 
-logger.info('End expire review')
+    logging.basicConfig(format='%(asctime)-6s: %(name)s - %(levelname)s'
+                               ' - %(message)s',
+                        filename='/var/log/gerrit/expire_reviews.log')
+
+    logger.info('Starting expire reviews')
+    logger.info('Connecting to Gerrit')
+
+    ssh = paramiko.SSHClient()
+    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
+    ssh.connect('localhost', username=GERRIT_USER,
+                key_filename=GERRIT_SSH_KEY, port=29418)
+
+    # Query all open with no activity for 2 weeks
+    logger.info('Searching no activity for 2 weeks')
+    stdin, stdout, stderr = ssh.exec_command(
+        'gerrit query --current-patch-set --format JSON status:open age:2w')
+
+    for line in stdout:
+        row = json.loads(line)
+        if 'rowCount' not in row:
+            expire_patch_set(ssh,
+                             row['currentPatchSet']['revision'],
+                             row['subject'],
+                             False)
+
+    # Query all reviewed with no activity for 1 week
+    logger.info('Searching no activity on negative review for 1 week')
+    stdin, stdout, stderr = ssh.exec_command(
+        'gerrit query --current-patch-set --all-approvals'
+        ' --format JSON status:reviewed age:1w')
+
+    for line in stdout:
+        row = json.loads(line)
+        if 'rowCount' not in row:
+            # Search for negative approvals
+            for approval in row['currentPatchSet']['approvals']:
+                if approval['value'] == '-1':
+                    expire_patch_set(ssh,
+                                     row['currentPatchSet']['revision'],
+                                     row['subject'],
+                                     True)
+                    break
+
+    logger.info('End expire review')
diff --git a/gerritx/cmd/fetch_remotes.py b/gerritx/cmd/fetch_remotes.py
old mode 100755
new mode 100644
index 6f8ab8b..f34e518
--- a/gerritx/cmd/fetch_remotes.py
+++ b/gerritx/cmd/fetch_remotes.py
@@ -33,6 +33,7 @@
 import shlex
 import yaml
 
+
 def run_command(cmd, status=False, env={}):
     cmd_list = shlex.split(str(cmd))
     newenv = os.environ
@@ -49,28 +50,30 @@
     return run_command(cmd, True, env)
 
 
-logging.basicConfig(level=logging.ERROR)
+def main():
+    logging.basicConfig(level=logging.ERROR)
 
-REPO_ROOT = os.environ.get('REPO_ROOT',
-                           '/home/gerrit2/review_site/git')
-PROJECTS_YAML = os.environ.get('PROJECTS_YAML',
-                               '/home/gerrit2/projects.yaml')
+    REPO_ROOT = os.environ.get('REPO_ROOT',
+                               '/home/gerrit2/review_site/git')
+    PROJECTS_YAML = os.environ.get('PROJECTS_YAML',
+                                   '/home/gerrit2/projects.yaml')
 
-(defaults, config) = [config for config in yaml.load_all(open(PROJECTS_YAML))]
+    (defaults, config) = [config for config in
+                          yaml.load_all(open(PROJECTS_YAML))]
 
-for section in config:
-    project = section['project']
+    for section in config:
+        project = section['project']
 
-    if 'remote' not in section:
-        continue
+        if 'remote' not in section:
+            continue
 
-    project_git = "%s.git" % project
-    os.chdir(os.path.join(REPO_ROOT, project_git))
+        project_git = "%s.git" % project
+        os.chdir(os.path.join(REPO_ROOT, project_git))
 
-    # Make sure that the specified remote exists
-    remote_url = section['remote']
-    # We could check if it exists first, but we're ignoring output anyway
-    # So just try to make it, and it'll either make a new one or do nothing
-    run_command("git remote add -f upstream %s" % remote_url)
-    # Fetch new revs from it
-    run_command("git remote update upstream")
+        # Make sure that the specified remote exists
+        remote_url = section['remote']
+        # We could check if it exists first, but we're ignoring output anyway
+        # So just try to make it, and it'll either make a new one or do nothing
+        run_command("git remote add -f upstream %s" % remote_url)
+        # Fetch new revs from it
+        run_command("git remote update upstream")
diff --git a/gerritx/cmd/manage_projects.py b/gerritx/cmd/manage_projects.py
old mode 100755
new mode 100644
index 9f5c518..fb1712b
--- a/gerritx/cmd/manage_projects.py
+++ b/gerritx/cmd/manage_projects.py
@@ -50,7 +50,6 @@
 import github
 import gerritlib.gerrit
 
-
 logging.basicConfig(level=logging.ERROR)
 log = logging.getLogger("manage_projects")
 
@@ -113,7 +112,7 @@
     status, _ = run_command("cp %s %s" %
                             (acl_config, acl_dest), status=True)
     if status == 0:
-        status = git_command(repo_path, "diff --quiet HEAD")
+        status = git_command(repo_path, "diff-index --quiet HEAD --")
         if status != 0:
             return True
     return False
@@ -121,14 +120,14 @@
 
 def push_acl_config(project, remote_url, repo_path, env={}):
     cmd = "commit -a -m'Update project config.' --author='Openstack Project " \
-            "Creator <openstack-infra@lists.openstack.org>'"
+          "Creator <openstack-infra@lists.openstack.org>'"
     status = git_command(repo_path, cmd)
     if status != 0:
         print "Failed to commit config for project: %s" % project
         return False
     status, out = git_command_output(repo_path,
-                         "push %s HEAD:refs/meta/config" %
-                         remote_url, env)
+                                     "push %s HEAD:refs/meta/config" %
+                                     remote_url, env)
     if status != 0:
         print "Failed to push config for project: %s" % project
         print out
@@ -194,134 +193,147 @@
     return dict(GIT_SSH=name)
 
 
-PROJECTS_YAML = os.environ.get('PROJECTS_YAML',
-                               '/home/gerrit2/projects.yaml')
-configs = [config for config in yaml.load_all(open(PROJECTS_YAML))]
-defaults = configs[0][0]
-default_has_issues = defaults.get('has-issues', False)
-default_has_downloads = defaults.get('has-downloads', False)
-default_has_wiki = defaults.get('has-wiki', False)
+def main():
 
-LOCAL_GIT_DIR = defaults.get('local-git-dir', '/var/lib/git')
-GERRIT_HOST = defaults.get('gerrit-host')
-GERRIT_USER = defaults.get('gerrit-user')
-GERRIT_KEY = defaults.get('gerrit-key')
-GITHUB_SECURE_CONFIG = defaults.get('github-config',
-                               '/etc/github/github-projects.secure.config')
+    PROJECTS_YAML = os.environ.get('PROJECTS_YAML',
+                                   '/home/gerrit2/projects.yaml')
+    configs = [config for config in yaml.load_all(open(PROJECTS_YAML))]
+    defaults = configs[0][0]
+    default_has_issues = defaults.get('has-issues', False)
+    default_has_downloads = defaults.get('has-downloads', False)
+    default_has_wiki = defaults.get('has-wiki', False)
 
-secure_config = ConfigParser.ConfigParser()
-secure_config.read(GITHUB_SECURE_CONFIG)
+    LOCAL_GIT_DIR = defaults.get('local-git-dir', '/var/lib/git')
+    GERRIT_HOST = defaults.get('gerrit-host')
+    GERRIT_USER = defaults.get('gerrit-user')
+    GERRIT_KEY = defaults.get('gerrit-key')
 
-# Project creation doesn't work via oauth
-ghub = github.Github(secure_config.get("github", "username"),
-                     secure_config.get("github", "password"))
-orgs = ghub.get_user().get_orgs()
-orgs_dict = dict(zip([o.login.lower() for o in orgs], orgs))
+    GITHUB_SECURE_CONFIG = defaults.get(
+        'github-config',
+        '/etc/github/github-projects.secure.config')
 
-gerrit = gerritlib.gerrit.Gerrit('localhost',
-                                 GERRIT_USER,
-                                 29418,
-                                 GERRIT_KEY)
-project_list = gerrit.listProjects()
-ssh_env = make_ssh_wrapper(GERRIT_USER, GERRIT_KEY)
-try:
+    secure_config = ConfigParser.ConfigParser()
+    secure_config.read(GITHUB_SECURE_CONFIG)
 
-    for section in configs[1]:
-        project = section['project']
-        options = section.get('options', dict())
-        description = section.get('description', None)
-        homepage = section.get('homepage', defaults.get('homepage', None))
-        upstream = section.get('upstream', None)
+    # Project creation doesn't work via oauth
+    ghub = github.Github(secure_config.get("github", "username"),
+                         secure_config.get("github", "password"))
+    orgs = ghub.get_user().get_orgs()
+    orgs_dict = dict(zip([o.login.lower() for o in orgs], orgs))
 
-        project_git = "%s.git" % project
-        project_dir = os.path.join(LOCAL_GIT_DIR, project_git)
+    gerrit = gerritlib.gerrit.Gerrit('localhost',
+                                     GERRIT_USER,
+                                     29418,
+                                     GERRIT_KEY)
+    project_list = gerrit.listProjects()
+    ssh_env = make_ssh_wrapper(GERRIT_USER, GERRIT_KEY)
+    try:
 
-        # Find the project's repo
-        project_split = project.split('/', 1)
-        if len(project_split) > 1:
-            repo_name = project_split[1]
-        else:
-            repo_name = project
-        has_issues = 'has-issues' in options or default_has_issues
-        has_downloads = 'has-downloads' in options or default_has_downloads
-        has_wiki = 'has-wiki' in options or default_has_wiki
-        try:
-            org = orgs_dict[project_split[0].lower()]
-        except KeyError:
-            # We do not have control of this github org ignore the project.
-            continue
-        try:
-            repo = org.get_repo(repo_name)
-        except github.GithubException:
-            repo = org.create_repo(repo_name,
-                                   homepage=homepage,
-                                   has_issues=has_issues,
-                                   has_downloads=has_downloads,
-                                   has_wiki=has_wiki)
-        if description:
-            repo.edit(repo_name, description=description)
-        if homepage:
-            repo.edit(repo_name, homepage=homepage)
+        for section in configs[1]:
+            project = section['project']
+            options = section.get('options', dict())
+            description = section.get('description', None)
+            homepage = section.get('homepage', defaults.get('homepage', None))
+            upstream = section.get('upstream', None)
 
-        repo.edit(repo_name, has_issues=has_issues,
-                  has_downloads=has_downloads,
-                  has_wiki=has_wiki)
+            project_git = "%s.git" % project
+            project_dir = os.path.join(LOCAL_GIT_DIR, project_git)
 
-        if 'gerrit' not in [team.name for team in repo.get_teams()]:
-            teams = org.get_teams()
-            teams_dict = dict(zip([t.name.lower() for t in teams], teams))
-            teams_dict['gerrit'].add_to_repos(repo)
-
-        remote_url = "ssh://localhost:29418/%s" % project
-        if project not in project_list:
-            tmpdir = tempfile.mkdtemp()
+            # Find the project's repo
+            project_split = project.split('/', 1)
+            if len(project_split) > 1:
+                repo_name = project_split[1]
+            else:
+                repo_name = project
+            has_issues = 'has-issues' in options or default_has_issues
+            has_downloads = 'has-downloads' in options or default_has_downloads
+            has_wiki = 'has-wiki' in options or default_has_wiki
             try:
-                repo_path = os.path.join(tmpdir, 'repo')
-                if upstream:
-                    run_command("git clone %(upstream)s %(repo_path)s" %
-                                dict(upstream=upstream, repo_path=repo_path))
-                else:
-                    run_command("git init %s" % repo_path)
-                    with open(os.path.join(repo_path,
-                                           ".gitreview"), 'w') as gitreview:
-                        gitreview.write("""
-[gerrit]
-host=%s
-port=29418
-project=%s
-""" % (GERRIT_HOST, project_git))
-                    git_command(repo_path, "add .gitreview")
-                    cmd = "commit -a -m'Added .gitreview' --author=" \
-                            "'Openstack Project Creator " \
-                            "<openstack-infra@lists.openstack.org>'"
-                    git_command(repo_path, cmd)
-                gerrit.createProject(project)
-
-                if not os.path.exists(project_dir):
-                    run_command("git --bare init %s" % project_dir)
-                    run_command("chown -R gerrit2:gerrit2 %s" % project_dir)
-
-                git_command(repo_path,
-                            "push --all %s" % remote_url,
-                            env=ssh_env)
-                git_command(repo_path,
-                            "push --tags %s" % remote_url, env=ssh_env)
-            finally:
-                run_command("rm -fr %s" % tmpdir)
-
-        if 'acl_config' in section:
-            tmpdir = tempfile.mkdtemp()
+                org = orgs_dict[project_split[0].lower()]
+            except KeyError:
+                # We do not have control of this github org ignore the project.
+                continue
             try:
-                repo_path = os.path.join(tmpdir, 'repo')
-                ret, _ = run_command_status("git init %s" % repo_path)
-                if ret != 0:
-                    continue
-                if (fetch_config(project, remote_url, repo_path, ssh_env) and
-                    copy_acl_config(project, repo_path,
-                                    section['acl_config']) and
-                    create_groups_file(project, gerrit, repo_path)):
-                    push_acl_config(project, remote_url, repo_path, ssh_env)
-            finally:
-                run_command("rm -fr %s" % tmpdir)
-finally:
-    os.unlink(ssh_env['GIT_SSH'])
+                repo = org.get_repo(repo_name)
+            except github.GithubException:
+                repo = org.create_repo(repo_name,
+                                       homepage=homepage,
+                                       has_issues=has_issues,
+                                       has_downloads=has_downloads,
+                                       has_wiki=has_wiki)
+            if description:
+                repo.edit(repo_name, description=description)
+            if homepage:
+                repo.edit(repo_name, homepage=homepage)
+
+            repo.edit(repo_name, has_issues=has_issues,
+                      has_downloads=has_downloads,
+                      has_wiki=has_wiki)
+
+            if 'gerrit' not in [team.name for team in repo.get_teams()]:
+                teams = org.get_teams()
+                teams_dict = dict(zip([t.name.lower() for t in teams], teams))
+                teams_dict['gerrit'].add_to_repos(repo)
+
+            remote_url = "ssh://localhost:29418/%s" % project
+            if project not in project_list:
+                tmpdir = tempfile.mkdtemp()
+                try:
+                    repo_path = os.path.join(tmpdir, 'repo')
+                    if upstream:
+                        run_command("git clone %(upstream)s %(repo_path)s" %
+                                    dict(upstream=upstream,
+                                         repo_path=repo_path))
+                    else:
+                        run_command("git init %s" % repo_path)
+                        with open(os.path.join(repo_path,
+                                               ".gitreview"),
+                                  'w') as gitreview:
+                            gitreview.write("""
+    [gerrit]
+    host=%s
+    port=29418
+    project=%s
+    """ % (GERRIT_HOST, project_git))
+                        git_command(repo_path, "add .gitreview")
+                        cmd = "commit -a -m'Added .gitreview' --author=" \
+                              "'Openstack Project Creator " \
+                              "<openstack-infra@lists.openstack.org>'"
+                        git_command(repo_path, cmd)
+                    gerrit.createProject(project)
+
+                    if not os.path.exists(project_dir):
+                        run_command("git --bare init %s" % project_dir)
+                        run_command("chown -R gerrit2:gerrit2 %s"
+                                    % project_dir)
+
+                    git_command(repo_path,
+                                "push --all %s" % remote_url,
+                                env=ssh_env)
+                    git_command(repo_path,
+                                "push --tags %s" % remote_url, env=ssh_env)
+                finally:
+                    run_command("rm -fr %s" % tmpdir)
+
+            if 'acl_config' in section:
+                tmpdir = tempfile.mkdtemp()
+                try:
+                    repo_path = os.path.join(tmpdir, 'repo')
+                    ret, _ = run_command_status("git init %s" % repo_path)
+                    if ret != 0:
+                        continue
+                    if (fetch_config(project,
+                                     remote_url,
+                                     repo_path,
+                                     ssh_env) and
+                        copy_acl_config(project, repo_path,
+                                        section['acl_config']) and
+                            create_groups_file(project, gerrit, repo_path)):
+                        push_acl_config(project,
+                                        remote_url,
+                                        repo_path,
+                                        ssh_env)
+                finally:
+                    run_command("rm -fr %s" % tmpdir)
+    finally:
+        os.unlink(ssh_env['GIT_SSH'])
diff --git a/gerritx/cmd/notify_impact.py b/gerritx/cmd/notify_impact.py
old mode 100755
new mode 100644
index 5c8ba8c..559fd7f
--- a/gerritx/cmd/notify_impact.py
+++ b/gerritx/cmd/notify_impact.py
@@ -34,6 +34,7 @@
 %s
 """
 
+
 def process_impact(git_log, args):
     """Notify mail list of impact"""
     email_content = EMAIL_TEMPLATE % (args.impact, args.change_url, git_log)
@@ -48,10 +49,12 @@
                args.dest_address, msg.as_string())
     s.quit()
 
+
 def impacted(git_log, impact_string):
     """Determine if a changes log indicates there is an impact"""
     return re.search(impact_string, git_log, re.IGNORECASE)
 
+
 def extract_git_log(args):
     """Extract git log of all merged commits"""
     cmd = ['git',
@@ -86,7 +89,3 @@
     # Process impacts found in git log
     if impacted(git_log, args.impact):
         process_impact(git_log, args)
-
-
-if __name__ == '__main__':
-    main()
diff --git a/gerritx/cmd/run_mirror.py b/gerritx/cmd/run_mirror.py
old mode 100755
new mode 100644
index b6b07e8..d6978de
--- a/gerritx/cmd/run_mirror.py
+++ b/gerritx/cmd/run_mirror.py
@@ -24,6 +24,7 @@
 import shlex
 import yaml
 
+
 def run_command(cmd, status=False, env={}):
     cmd_list = shlex.split(str(cmd))
     newenv = os.environ
@@ -40,42 +41,45 @@
     return run_command(cmd, True, env)
 
 
-logging.basicConfig(level=logging.ERROR)
+def main():
 
-PROJECTS_YAML = os.environ.get('PROJECTS_YAML',
-                               '/etc/openstackci/projects.yaml')
-PIP_TEMP_DOWNLOAD = os.environ.get('PIP_TEMP_DOWNLOAD',
-                                   '/var/lib/pip-download')
-GIT_SOURCE = os.environ.get('GIT_SOURCE', 'https://github.com')
-pip_command = '/usr/local/bin/pip install -M -U -I --exists-action=w ' \
-              '--no-install %s'
+    logging.basicConfig(level=logging.ERROR)
 
-run_command(pip_command % "pip")
+    PROJECTS_YAML = os.environ.get('PROJECTS_YAML',
+                                   '/etc/openstackci/projects.yaml')
+    PIP_TEMP_DOWNLOAD = os.environ.get('PIP_TEMP_DOWNLOAD',
+                                       '/var/lib/pip-download')
+    GIT_SOURCE = os.environ.get('GIT_SOURCE', 'https://github.com')
+    pip_command = '/usr/local/bin/pip install -M -U -I --exists-action=w ' \
+                  '--no-install %s'
 
-(defaults, config) = [config for config in yaml.load_all(open(PROJECTS_YAML))]
+    run_command(pip_command % "pip")
 
-for section in config:
-    project = section['project']
+    (defaults, config) = [config for config in
+                          yaml.load_all(open(PROJECTS_YAML))]
 
-    os.chdir(PIP_TEMP_DOWNLOAD)
-    short_project = project.split('/')[1]
-    if not os.path.isdir(short_project):
-        run_command("git clone %s/%s.git %s" % (GIT_SOURCE, project,
-                                                short_project))
-    os.chdir(short_project)
-    run_command("git fetch origin")
+    for section in config:
+        project = section['project']
 
-    for branch in run_command("git branch -a").split("\n"):
-        branch = branch.strip()
-        if (not branch.startswith("remotes/origin")
-            or "origin/HEAD" in branch):
-            continue
-        run_command("git reset --hard %s" % branch)
-        run_command("git clean -x -f -d -q")
-        print("*********************")
-        print("Fetching pip requires for %s:%s" % (project, branch))
-        for requires_file in ("tools/pip-requires", "tools/test-requires"):
-            if os.path.exists(requires_file):
-                stanza = "-r %s" % requires_file
-                run_command(pip_command % stanza)
+        os.chdir(PIP_TEMP_DOWNLOAD)
+        short_project = project.split('/')[1]
+        if not os.path.isdir(short_project):
+            run_command("git clone %s/%s.git %s" % (GIT_SOURCE, project,
+                                                    short_project))
+        os.chdir(short_project)
+        run_command("git fetch origin")
 
+        for branch in run_command("git branch -a").split("\n"):
+            branch = branch.strip()
+            if (not branch.startswith("remotes/origin")
+                    or "origin/HEAD" in branch):
+                continue
+            run_command("git reset --hard %s" % branch)
+            run_command("git clean -x -f -d -q")
+            print("*********************")
+            print("Fetching pip requires for %s:%s" % (project, branch))
+            for requires_file in ("tools/pip-requires",
+                                  "tools/test-requires"):
+                if os.path.exists(requires_file):
+                    stanza = "-r %s" % requires_file
+                    run_command(pip_command % stanza)
diff --git a/gerritx/cmd/update_blueprint.py b/gerritx/cmd/update_blueprint.py
old mode 100755
new mode 100644
index 9c18f1d..64a2e54
--- a/gerritx/cmd/update_blueprint.py
+++ b/gerritx/cmd/update_blueprint.py
@@ -29,34 +29,39 @@
 import MySQLdb
 
 BASE_DIR = '/home/gerrit2/review_site'
-GERRIT_CACHE_DIR = os.path.expanduser(os.environ.get('GERRIT_CACHE_DIR',
-                                '~/.launchpadlib/cache'))
-GERRIT_CREDENTIALS = os.path.expanduser(os.environ.get('GERRIT_CREDENTIALS',
-                                '~/.launchpadlib/creds'))
+GERRIT_CACHE_DIR = os.path.expanduser(
+    os.environ.get('GERRIT_CACHE_DIR',
+                   '~/.launchpadlib/cache'))
+GERRIT_CREDENTIALS = os.path.expanduser(
+    os.environ.get('GERRIT_CREDENTIALS',
+                   '~/.launchpadlib/creds'))
 GERRIT_CONFIG = os.environ.get('GERRIT_CONFIG',
-                                 '/home/gerrit2/review_site/etc/gerrit.config')
+                               '/home/gerrit2/review_site/etc/gerrit.config')
+GERRIT_SECURE_CONFIG_DEFAULT = '/home/gerrit2/review_site/etc/secure.config'
 GERRIT_SECURE_CONFIG = os.environ.get('GERRIT_SECURE_CONFIG',
-                                 '/home/gerrit2/review_site/etc/secure.config')
+                                      GERRIT_SECURE_CONFIG_DEFAULT)
 SPEC_RE = re.compile(r'(blueprint|bp)\s*[#:]?\s*(\S+)', re.I)
 BODY_RE = re.compile(r'^\s+.*$')
 
+
 def get_broken_config(filename):
     """ gerrit config ini files are broken and have leading tabs """
     text = ""
-    with open(filename,"r") as conf:
+    with open(filename, "r") as conf:
         for line in conf.readlines():
             text = "%s%s" % (text, line.lstrip())
 
     fp = StringIO.StringIO(text)
-    c=ConfigParser.ConfigParser()
+    c = ConfigParser.ConfigParser()
     c.readfp(fp)
     return c
 
 GERRIT_CONFIG = get_broken_config(GERRIT_CONFIG)
 SECURE_CONFIG = get_broken_config(GERRIT_SECURE_CONFIG)
 DB_USER = GERRIT_CONFIG.get("database", "username")
-DB_PASS = SECURE_CONFIG.get("database","password")
-DB_DB = GERRIT_CONFIG.get("database","database")
+DB_PASS = SECURE_CONFIG.get("database", "password")
+DB_DB = GERRIT_CONFIG.get("database", "database")
+
 
 def update_spec(launchpad, project, name, subject, link, topic=None):
     # For testing, if a project doesn't match openstack/foo, use
@@ -66,7 +71,8 @@
         project = 'openstack-ci'
 
     spec = launchpad.projects[project].getSpecification(name=name)
-    if not spec: return
+    if not spec:
+        return
 
     if spec.whiteboard:
         wb = spec.whiteboard.strip()
@@ -74,30 +80,34 @@
         wb = ''
     changed = False
     if topic:
-        topiclink = '%s/#q,topic:%s,n,z' % (link[:link.find('/',8)],
+        topiclink = '%s/#q,topic:%s,n,z' % (link[:link.find('/', 8)],
                                             topic)
         if topiclink not in wb:
             wb += "\n\n\nGerrit topic: %(link)s" % dict(link=topiclink)
             changed = True
 
     if link not in wb:
-        wb += "\n\n\nAddressed by: %(link)s\n    %(subject)s\n" % dict(subject=subject,
-                                                                      link=link)
+        wb += ("\n\n\nAddressed by: {link}\n"
+               "    {subject}\n").format(subject=subject,
+                                         link=link)
         changed = True
 
     if changed:
         spec.whiteboard = wb
         spec.lp_save()
 
+
 def find_specs(launchpad, dbconn, args):
-    git_log = subprocess.Popen(['git',
-                                '--git-dir=' + BASE_DIR + '/git/' + args.project + '.git',
-                                'log', '--no-merges',
+    git_dir_arg = '--git-dir={base_dir}/git/{project}.git'.format(
+        base_dir=BASE_DIR,
+        project=args.project)
+    git_log = subprocess.Popen(['git', git_dir_arg, 'log', '--no-merges',
                                 args.commit + '^1..' + args.commit],
                                stdout=subprocess.PIPE).communicate()[0]
 
     cur = dbconn.cursor()
-    cur.execute("select subject, topic from changes where change_key=%s", args.change)
+    cur.execute("select subject, topic from changes where change_key=%s",
+                args.change)
     subject, topic = cur.fetchone()
     specs = set([m.group(2) for m in SPEC_RE.finditer(git_log)])
 
@@ -109,6 +119,7 @@
         update_spec(launchpad, args.project, spec, subject,
                     args.change_url, topic)
 
+
 def main():
     parser = argparse.ArgumentParser()
     parser.add_argument('hook')
@@ -128,12 +139,9 @@
 
     launchpad = Launchpad.login_with('Gerrit User Sync', LPNET_SERVICE_ROOT,
                                      GERRIT_CACHE_DIR,
-                                     credentials_file = GERRIT_CREDENTIALS,
+                                     credentials_file=GERRIT_CREDENTIALS,
                                      version='devel')
 
-    conn = MySQLdb.connect(user = DB_USER, passwd = DB_PASS, db = DB_DB)
+    conn = MySQLdb.connect(user=DB_USER, passwd=DB_PASS, db=DB_DB)
 
     find_specs(launchpad, conn, args)
-
-if __name__ == '__main__':
-    main()
diff --git a/gerritx/cmd/update_bug.py b/gerritx/cmd/update_bug.py
old mode 100755
new mode 100644
index 9479a81..d17bbdd
--- a/gerritx/cmd/update_bug.py
+++ b/gerritx/cmd/update_bug.py
@@ -26,10 +26,12 @@
 
 
 BASE_DIR = '/home/gerrit2/review_site'
-GERRIT_CACHE_DIR = os.path.expanduser(os.environ.get('GERRIT_CACHE_DIR',
-                                '~/.launchpadlib/cache'))
-GERRIT_CREDENTIALS = os.path.expanduser(os.environ.get('GERRIT_CREDENTIALS',
-                                '~/.launchpadlib/creds'))
+GERRIT_CACHE_DIR = os.path.expanduser(
+    os.environ.get('GERRIT_CACHE_DIR',
+                   '~/.launchpadlib/cache'))
+GERRIT_CREDENTIALS = os.path.expanduser(
+    os.environ.get('GERRIT_CREDENTIALS',
+                   '~/.launchpadlib/creds'))
 
 
 def add_change_proposed_message(bugtask, change_url, project, branch):
@@ -112,7 +114,7 @@
         'openstack-ci/gerrit': 'openstack-ci',
         'openstack-ci/lodgeit': 'openstack-ci',
         'openstack-ci/meetbot': 'openstack-ci',
-        }
+    }
     return project_map.get(full_project_name, short_project(full_project_name))
 
 
@@ -127,7 +129,7 @@
         'openstack/openstack-ci-puppet',
         'openstack/openstack-manuals',
         'openstack/tempest',
-        ]
+    ]
 
 
 def process_bugtask(launchpad, bugtask, git_log, args):
@@ -147,7 +149,7 @@
             # Look for a related task matching the series
             for reltask in bugtask.related_tasks:
                 if (reltask.bug_target_name.endswith("/" + series) and
-                    reltask.status != u'Fix Released'):
+                        reltask.status != u'Fix Released'):
                     # Use fixcommitted if there is any
                     set_fix_committed(reltask)
                     break
@@ -168,7 +170,8 @@
             series = args.branch[7:]
             for reltask in bugtask.related_tasks:
                 if (reltask.bug_target_name.endswith("/" + series) and
-                    reltask.status not in [u'Fix Committed', u'Fix Released']):
+                        reltask.status not in [u'Fix Committed',
+                                               u'Fix Released']):
                     set_in_progress(reltask, launchpad,
                                     args.uploader, args.change_url)
                     break
@@ -238,7 +241,3 @@
     # Process bugtasks found in git log
     for bugtask in find_bugs(launchpad, git_log, args):
         process_bugtask(launchpad, bugtask, git_log, args)
-
-
-if __name__ == '__main__':
-    main()