[sysadmin-bin] Simplify main function



commit 33a3f0d66e4868e91a34b0bc871de1fba9cc95d8
Author: Bartłomiej Piotrowski <bpiotrowski gnome org>
Date:   Tue Oct 29 08:28:59 2019 +0100

    Simplify main function

 git/post-receive-mirror-github | 144 ++++++++++++++---------------------------
 1 file changed, 50 insertions(+), 94 deletions(-)
---
diff --git a/git/post-receive-mirror-github b/git/post-receive-mirror-github
index 97c50f1..3ffc1f8 100755
--- a/git/post-receive-mirror-github
+++ b/git/post-receive-mirror-github
@@ -72,9 +72,11 @@ class GitHub:
 
         return True
 
-    def create_github_repo(self, name, description, homepage):
-        if self.check_if_repo_exists(name):
-            return
+    def create_github_repo(self, **kwargs):
+        required_parameters = ['name', 'description', 'homepage']
+        if not all([arg in kwargs for arg in required_parameters]):
+            raise TypeError("Function requires name, description and homepage keyword arguments")
+
         payload = json.dumps({
                              'name': self.normalize_name(name),
                              'description': description,
@@ -103,7 +105,17 @@ class GitHub:
 
         raise Exception("There was an error attempting to update the repo %s in github:\n\nStatus: 
%d\nText:\n%s" % (name, rq.status_code, rq.text))
 
-    def fetch_github_repo(self, name):
+    def get_branches(self, name):
+        api_url = 'https://api.github.com/repos/{}/{}'.format(self.organization, name)
+        rq = requests.get("{}/branches".format(api_url), auth=(self.user, self.pw))
+
+        if rq.status_code != 200:
+            raise Exception("There was an error attempting to fetch branches of the repo %s in 
github:\n\nStatus: %d\nText:\n%s" % (name, rq.status_code, rq.text))
+
+        branches = {branch['name'] for branch in rq.json()}
+        return branches
+
+    def get_github_repo(self, name):
         api_url = 'https://api.github.com/repos/{}/{}'.format(self.organization, name)
 
         rq = requests.get(api_url, auth=(self.user, self.pw))
@@ -114,13 +126,17 @@ class GitHub:
         homepage = rq.json()['homepage']
         default_branch = rq.json()['default_branch']
 
+        api_url = 'https://api.github.com/repos/{}/{}'.format(self.organization, name)
         rq = requests.get("{}/branches".format(api_url), auth=(self.user, self.pw))
-        branches = {branch['name'] for branch in rq.json()}
+        branches = self.get_branches(name)
 
-        if rq.status_code != 200:
-            raise Exception("There was an error attempting to fetch branches of the repo %s in 
github:\n\nStatus: %d\nText:\n%s" % (name, rq.status_code, rq.text))
-
-        return description, homepage, default_branch, branches
+        ret = {
+                'description': description,
+                'homepage': homepage,
+                'default_branch': default_branch,
+                'branches': branches
+        }
+        return ret
 
 
     def normalize_name(self, name):
@@ -141,7 +157,7 @@ def get_repo_name():
         repo_name = repo_name[0:-4]
     return repo_name
 
-def get_repo_settings(repo_name):
+def get_doap_settings(repo_name):
     nss = {'doap': 'http://usefulinc.com/ns/doap#',
            'rdf':  'http://www.w3.org/1999/02/22-rdf-syntax-ns#'}
 
@@ -178,98 +194,38 @@ def get_repo_settings(repo_name):
 
 
 def main():
-    gh = GitHub(ORGANIZATION)
     repo_name = get_repo_name()
-    github_name = gh.normalize_name(repo_name)
-
     if repo_name.endswith('.wiki'):
         sys.exit(1)
 
-    settings = get_repo_settings(repo_name)
-    repo_exists = gh.check_if_repo_exists(repo_name)
+    gh = GitHub(ORGANIZATION)
+    doap_settings = get_doap_settings(repo_name)
+    github_repo_exists = gh.check_if_repo_exists(repo_name)
+
+    if not github_repo_exists:
+        gh.create_github_repo(**doap_settings)
+
+    github_settings = get_github_repo(repo_name)
+
+    if github_settings['description'] != doap_settings['description']:
+        gh.update_github_repo(repo_name, 'description', doap_settings["description"])
+
+    if github_settings['homepage'] != doap_settings['homepage']:
+        gh.update_github_repo(repo_name, 'homepage', doap_settings["homepage"])
 
-    # Avoid master here as we will later push it under different name
     refs = ["refs/heads/{}".format(branch) for branch in settings['branches'] if branch != "master"]
 
-    if repo_exists:
-        description, homepage, default_branch, branches = gh.fetch_github_repo(github_name)
-
-        if description != settings["description"]:
-            gh.update_github_repo(github_name, 'description', settings["description"])
-
-        if homepage != settings["homepage"]:
-            gh.update_github_repo(github_name, 'homepage', settings["homepage"])
-    else:
-        gh.create_github_repo(settings["name"], settings["description"], settings["homepage"])
-        default_branch = settings["default_branch"]
-
-    if default_branch != 'mainline':
-        for organization in [gh.organization] + ADDITIONAL_ORGANIZATIONS.get(repo_name, []):
-            if refs:
-                try:
-                    command = 'git push --force git github com:{}/{} {}:mainline {}'.format(organization, 
github_name, settings['default_branch'], " ".join(refs))
-                    out = tempfile.NamedTemporaryFile(prefix="github",suffix="std")
-                    err = tempfile.NamedTemporaryFile(prefix="github",suffix="err")
-                    subprocess.check_call(shlex.split(command), stderr=err, stdout=out)
-                    out.close()
-                    err.close()
-                except subprocess.CalledProcessError:
-                    out = open(out.name, "r")
-                    err = open(err.name, "r")
-                    error_msg = """
-Error trying to push repo {}/{}
-Command: {}
-STDOUT: {}
-STDERR: {}
-""".format(organization, repo_name, out.read(), err.read(), command)
-                    raise Exception(error_msg)
-
-        _, _, _, branches = gh.fetch_github_repo(github_name)
-        if "mainline" in branches:
-            gh.update_github_repo(github_name, 'default_branch', 'mainline')
-
-    if default_branch == 'mainline':
-        for organization in [gh.organization] + ADDITIONAL_ORGANIZATIONS.get(repo_name, []):
-            if refs:
-                try:
-                    command = 'git push --mirror git github com:{}/{}'.format(organization, github_name)
-                    out = tempfile.NamedTemporaryFile(prefix="github",suffix="std")
-                    err = tempfile.NamedTemporaryFile(prefix="github",suffix="err")
-                    subprocess.check_call(shlex.split(command), stderr=err, stdout=out)
-                    out.close()
-                    err.close()
-                except subprocess.CalledProcessError:
-                    out = open(out.name, "r")
-                    err = open(err.name, "r")
-                    error_msg = """
-Error trying to push repo {}/{}
-STDOUT: {}
-STDERR: {}
-""".format(organization, repo_name, out.read(), err.read())
-                    raise Exception(error_msg)
-
-
-    # Drop master branch in separate loop as GitHub API disallows to drop the
-    # default branch and also expects new default branch to exists
-    for organization in [gh.organization] + ADDITIONAL_ORGANIZATIONS.get(repo_name, []):
-        if 'master' in branches:
-            try:
-                command = 'git push --force git github com:{}/{} :master'.format(organization, github_name)
-                out = tempfile.NamedTemporaryFile(prefix="github",suffix="std")
-                err = tempfile.NamedTemporaryFile(prefix="github",suffix="err")
-                subprocess.check_call(shlex.split(command), stderr=err, stdout=out)
-                out.close()
-                err.close()
-            except subprocess.CalledProcessError:
-                out = open(out.name, "r")
-                err = open(err.name, "r")
-                error_msg = """
-Error trying to push repo {}/{}
-STDOUT: {}
-STDERR: {}
-""".format(organization, repo_name, out.read(), err.read())
-                raise Exception(error_msg)
+    github_repo_name = gh.normalize_name(repo_name)
+    push_command = "git push --force git github com:{}/{} {}:mainline {}"
+    command = push_command.format(gh.organization, github_repo_name, doap_settings['default_branch'], " 
".join(refs))
+    subprocess.run(command, shell=True, check=True)
+
+    if github_settings['default_branch'] != "mainline":
+        gh.update_github_repo(repo_name, 'default_branch', "mainline")
+        subprocess.run("git push --force git github com:{}/{} :master".format(gh.organization, 
github_repo_name), shell=True, check=True)
 
+    for org in ADITIONAL_ORGANIZATIONS.get(repo_name, []):
+        subprocess.run("git push --mirror git github com:{}/{}".format(org, github_repo_name), shell=True, 
check=True)
 
 
 if __name__ == "__main__":


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]