]> Frank Brehm's Git Trees - pixelpark/puppetmaster-webhooks.git/commitdiff
Completed lib/webhooks/base_app.py
authorFrank Brehm <frank.brehm@pixelpark.com>
Wed, 15 Feb 2017 10:39:40 +0000 (11:39 +0100)
committerFrank Brehm <frank.brehm@pixelpark.com>
Wed, 15 Feb 2017 10:39:40 +0000 (11:39 +0100)
lib/webhooks/__init__.py
lib/webhooks/base_app.py

index 96df6a76a1df32c5480aaed9572d0216c6286f05..ff30aa1e3c1690808682bfe22e149c37c2523e6c 100644 (file)
@@ -1,6 +1,6 @@
 #!/bin/env python3
 # -*- coding: utf-8 -*-
 
-__version__ = '0.4.1'
+__version__ = '0.4.2'
 
 # vim: ts=4 et list
index c3ecad1274c93f28605f20a43dac8dea61957655..4f6b5f92d753c58f60d7873a69f4d653e1e0b930 100644 (file)
@@ -212,6 +212,13 @@ class BaseHookApp(object):
             help='Increase the verbosity level',
         )
 
+        arg_parser.add_argument(
+            "-C", '--cgi',
+            action='store_true',
+            dest='cgi',
+            help='Enforces behaviour as called as a CGI script.',
+        )
+
         arg_parser.add_argument(
             "-h", "--help",
             action='help',
@@ -245,6 +252,10 @@ class BaseHookApp(object):
             if self.cmdline_args.verbose > self._start_verbose:
                 self._start_verbose = self.cmdline_args.verbose
 
+        if self.cmdline_args.cgi:
+            if not os.environ.get('REQUEST_METHOD', None):
+                os.environ['REQUEST_METHOD'] = 'GET'
+
     # -------------------------------------------------------------------------
     def read_config(self):
         """Reading configuration from different YAML files."""
@@ -369,7 +380,7 @@ class BaseHookApp(object):
 
             se = None
             try:
-                se = file(self.error_logfile, 'ab', 0)
+                se = open(self.error_logfile, 'ab', 0)
             except Exception as e:
                 msg = "Could not open error logfile {f!r}: {e}\n\n".format(
                     f=self.error_logfile, e=e)
@@ -440,13 +451,9 @@ class BaseHookApp(object):
             if self.verbose > 1:
                 LOG.debug("Got JSON data:\n{}".format(pp(self.json_data)))
 
-            self.ref = self.json_data['ref'].split('/')[-1]
-            self.namespace = self.json_data['project']['namespace']
-            self.name = self.json_data['project']['name']
-            self.full_name = self.json_data['project']['path_with_namespace']
-
             try:
-                self.run()
+                if self.pre_run():
+                    self.run()
             except Exception as e:
                 msg = "Got a {n} performing the deploy: {e}".format(n=e.__class__.__name__, e=e)
                 msg += "\n\nTraceback:\n{}".format(traceback.format_exc())
@@ -460,6 +467,50 @@ class BaseHookApp(object):
             LOG.info("Finished.")
             sys.exit(0)
 
+    # -------------------------------------------------------------------------
+    def pre_run(self):
+
+        self.ref = self.json_data['ref'].split('/')[-1]
+        self.namespace = self.json_data['project']['namespace']
+        self.name = self.json_data['project']['name']
+        self.full_name = self.json_data['project']['path_with_namespace']
+
+        if self.special_chars_re.search(self.name):
+            msg = "Project {!r}: Received special characters in module name".format(
+                self.full_name)
+            return False
+
+        committers = []
+        timeformat = '%Y-%m-%dT%H:%M:%S%z'
+        for commit in self.json_data['commits']:
+            ts = commit['timestamp'].split('+')
+            ts_str = ts[0]
+            if len(ts) > 1:
+                ts_str += '+' + ts[1].replace(':', '').ljust(4, '0')
+            else:
+                ts_str += '+0000'
+            timestamp = datetime.datetime.strptime(ts_str, timeformat)
+            email = commit['author']['email']
+            committers.append((timestamp, email))
+
+        if committers:
+            committers.sort()
+            if self.verbose > 1:
+                LOG.debug("Got committers: {}".format(pp(committers)))
+            self.mail_to_addresses.append(committers[-1][1])
+        else:
+            LOG.debug("No committers found to append a mail address.")
+
+        if 'git_ssh_url' in self.json_data['project']:
+            self.git_ssh_url = self.json_data['project']['git_ssh_url']
+        else:
+            self.git_ssh_url = 'git@git.pixelpark.com:{ns}/{n}.git'.format(
+                ns=self.namespace, n=self.name)
+        LOG.info("Executing webhook {a!r} for Git SSH URL {u!r}, branch {b!r}.".format(
+            a=self.appname, u=self.git_ssh_url, b=self.ref))
+
+        return True
+
     # -------------------------------------------------------------------------
     def send_error_msgs(self, project='undefined'):