[X2Go-Commits] [maintenancescripts] 01/05: git/hooks/update-script._irkerhook.py_: merge in upstream changes (mostly Python-3-related).

git-admin at x2go.org git-admin at x2go.org
Wed Jan 1 16:08:42 CET 2020


This is an automated email from the git hooks/post-receive script.

x2go pushed a commit to branch master
in repository maintenancescripts.

commit ca74520c8bf56505b23359c14f24765aa0d73afa
Author: Mihai Moldovan <ionic at ionic.de>
Date:   Wed Jan 1 14:34:02 2020 +0100

    git/hooks/update-script._irkerhook.py_: merge in upstream changes (mostly Python-3-related).
---
 git/hooks/update-script._irkerhook.py_ | 73 +++++++++++++++++++++++-----------
 1 file changed, 50 insertions(+), 23 deletions(-)

diff --git a/git/hooks/update-script._irkerhook.py_ b/git/hooks/update-script._irkerhook.py_
index 84525d4..71c1c3b 100755
--- a/git/hooks/update-script._irkerhook.py_
+++ b/git/hooks/update-script._irkerhook.py_
@@ -18,12 +18,14 @@
 # does not override it.
 #
 # SPDX-License-Identifier: BSD-2-Clause
+from __future__ import print_function, absolute_import
+
 default_server = "ionic.de"
 IRKER_PORT = 10614
 
 # The default service used to turn your web-view URL into a tinyurl so it
 # will take up less space on the IRC notification line.
-default_tinyifier = "http://tinyurl.com/api-create.php?url="
+default_tinyifier = u"http://tinyurl.com/api-create.php?url="
 
 # Map magic urlprefix values to actual URL prefixes.
 urlprefixmap = {
@@ -33,7 +35,7 @@ urlprefixmap = {
     }
 
 # By default, ship to the freenode #commits list
-default_channels = "irc://chat.freenode.net/#x2go"
+default_channels = u"irc://chat.freenode.net/#x2go"
 
 #
 # No user-serviceable parts below this line:
@@ -41,14 +43,25 @@ default_channels = "irc://chat.freenode.net/#x2go"
 
 version = "2.17"
 
-import os, sys, socket, urllib2, subprocess, locale, datetime, re
+import os, sys, socket, subprocess, locale, datetime, re
 from pipes import quote as shellquote
 
+try:
+    from urllib2 import urlopen, HTTPError
+except ImportError:
+    from urllib.error import HTTPError
+    from urllib.request import urlopen
+
 try:
     import simplejson as json	# Faster, also makes us Python-2.5-compatible
 except ImportError:
     import json
 
+if sys.version_info.major == 2:
+    string_type = unicode
+else:
+    string_type = str
+
 try:
     getstatusoutput = subprocess.getstatusoutput
 except AttributeError:
@@ -56,7 +69,10 @@ except AttributeError:
     getstatusoutput = commands.getstatusoutput
 
 def do(command):
-    return unicode(getstatusoutput(command)[1], locale.getlocale()[1] or 'UTF-8').encode(locale.getlocale()[1] or 'UTF-8')
+    if sys.version_info.major == 2:
+        return string_type(getstatusoutput(command)[1], locale.getlocale()[1] or 'UTF-8')
+    else:
+        return getstatusoutput(command)[1]
 
 class Commit:
     def __init__(self, extractor, commit):
@@ -72,7 +88,14 @@ class Commit:
         self.author_date = None
         self.commit_date = None
         self.__dict__.update(extractor.__dict__)
-    def __unicode__(self):
+
+        if sys.version_info.major == 2:
+            # Convert __str__ to __unicode__ for python 2
+            self.__unicode__ = self.__str__
+            # Not really needed, but maybe useful for debugging
+            self.__str__ = lambda x: x.__unicode__().encode('utf-8')
+
+    def __str__(self):
         "Produce a notification string from this commit."
         if self.urlprefix.lower() == "none":
             self.url = ""
@@ -81,12 +104,12 @@ class Commit:
             webview = (urlprefix % self.__dict__) + self.commit
             try:
                 # See it the url is accessible
-                res = urllib2.urlopen(webview)
+                res = urlopen(webview)
                 if self.tinyifier and self.tinyifier.lower() != "none":
                     try:
                         # Didn't get a retrieval error on the web
                         # view, so try to tinyify a reference to it.
-                        self.url = urllib2.urlopen(self.tinyifier + webview).read()
+                        self.url = urlopen(self.tinyifier + webview).read()
                         try:
                             self.url = self.url.decode('UTF-8')
                         except UnicodeError:
@@ -95,7 +118,7 @@ class Commit:
                         self.url = webview
                 else:
                     self.url = webview
-            except urllib2.HTTPError as e:
+            except HTTPError as e:
                 if e.code == 401:
                     # Authentication error, so we assume the view is valid
                     self.url = webview
@@ -116,7 +139,7 @@ class Commit:
         if not isinstance(self.mail, unicode):
             self.mail = unicode(self.mail, 'utf-8')
         res = self.template % self.__dict__
-        return unicode(res, 'UTF-8') if not isinstance(res, unicode) else res
+        return string_type(res, 'UTF-8') if not isinstance(res, string_type) else res
 
 class GenericExtractor:
     "Generic class for encapsulating data from a VCS."
@@ -249,20 +272,20 @@ class GitExtractor(GenericExtractor):
         GenericExtractor.__init__(self, arguments)
         # Get all global config variables
         #self.project = do("git config --get irker.project")
-        self.project = "X2Go"
+        self.project = u"X2Go"
         self.repo = do("git config --get irker.repo")
         self.server = do("git config --get irker.server")
         self.channels = do("git config --get irker.channels")
         self.email = do("git config --get irker.email")
         #self.tcp = do("git config --bool --get irker.tcp")
         self.tcp = True
-        self.template = '%(bold)s%(project)s:%(reset)s %(green)s%(author)s%(reset)s %(repo)s:%(yellow)s%(branch)s%(reset)s * %(red)s%(url)s%(reset)s / %(bold)s%(files)s%(reset)s:\n%(logmsg)s'
+        self.template = u'%(bold)s%(project)s:%(reset)s %(green)s%(author)s%(reset)s %(repo)s:%(yellow)s%(branch)s%(reset)s * %(red)s%(url)s%(reset)s / %(bold)s%(files)s%(reset)s:\n%(logmsg)s'
         self.tinyifier = do("git config --get irker.tinyifier") or default_tinyifier
         #self.color = do("git config --get irker.color")
-        self.color = "mIRC"
-        self.urlprefix = do("git config --get irker.urlprefix") or "gitweb"
+        self.color = u"mIRC"
+        self.urlprefix = do("git config --get irker.urlprefix") or u"gitweb"
         #self.cialike = do("git config --get irker.cialike")
-        self.cialike = "60"
+        self.cialike = u"60"
         self.filtercmd = do("git config --get irker.filtercmd")
         # These are git-specific
         self.refname = do("git symbolic-ref HEAD 2>/dev/null")
@@ -326,12 +349,12 @@ class GitExtractor(GenericExtractor):
 
         if len(tmp) > 6:
             tmp = tmp[:5]
-            tmp.append ("%(lightgrey)s... message truncated%(reset)s" % self.__dict__)
+            tmp.append (u"%(lightgrey)s... message truncated%(reset)s" % self.__dict__)
 
         commit.logmsg = "\n".join(tmp)
 
         if self.rebase != '':
-            commit.logmsg = ("%(cyan)sRebase detected.%(reset)s\nOld ref: " + self.rebase + "\nNew HEAD: " + commit.commit + "\nPlease check the URL for more information.") % self.__dict__
+            commit.logmsg = (u"%(cyan)sRebase detected.%(reset)s\nOld ref: " + self.rebase + "\nNew HEAD: " + commit.commit + "\nPlease check the URL for more information.") % self.__dict__
         # This discards the part of the author's address after @.
         # Might be be nice to ship the full email address, if not
         # for spammers' address harvesters - getting this wrong
@@ -472,6 +495,10 @@ extractors = [GitExtractor, HgExtractor, SvnExtractor]
 
 # VCS-dependent code ends here
 
+def convert_message(message):
+    """Convert the message to bytes to send to the socket"""
+    return message.encode(locale.getlocale()[1] or 'UTF-8') + b'\n'
+
 def ship(extractor, commit, debug):
     "Ship a notification for the specified commit."
     metadata = extractor.commit_factory(commit)
@@ -504,10 +531,10 @@ def ship(extractor, commit, debug):
     # purposes the commit text is more important.  If it's still too long
     # there's nothing much can be done other than ship it expecting the IRC
     # server to truncate.
-    privmsg = unicode(metadata)
+    privmsg = string_type(metadata)
     if len(privmsg) > 510:
         metadata.files = ""
-        privmsg = unicode(metadata)
+        privmsg = string_type(metadata)
 
     # Anti-spamming guard.  It's deliberate that we get maxchannels not from
     # the user-filtered metadata but from the extractor data - means repo
@@ -519,7 +546,7 @@ def ship(extractor, commit, debug):
     # Ready to ship.
     message = json.dumps({"to": channels, "privmsg": privmsg})
     if debug:
-        print message
+        print(message)
     elif channels:
         try:
             if extractor.email:
@@ -541,16 +568,16 @@ Subject: irker json
                 try:
                     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                     sock.connect((extractor.server or default_server, IRKER_PORT))
-                    sock.sendall(message + "\n")
+                    sock.sendall(convert_message(message))
                 finally:
                     sock.close()
             else:
                 try:
                     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
-                    sock.sendto(message + "\n", (extractor.server or default_server, IRKER_PORT))
+                    sock.sendto(convert_message(message), (extractor.server or default_server, IRKER_PORT))
                 finally:
                     sock.close()
-        except socket.error, e:
+        except socket.error as e:
             sys.stderr.write("%s\n" % e)
 
 if __name__ == "__main__":
@@ -561,7 +588,7 @@ if __name__ == "__main__":
         if arg == '-n':
             notify = False
         elif arg == '-V':
-            print "irkerhook.py: version", version
+            print("irkerhook.py: version", version)
             sys.exit(0)
         elif arg.startswith("--repository="):
             repository = arg[13:]

--
Alioth's /home/x2go-admin/maintenancescripts/git/hooks/post-receive-email on /srv/git/code.x2go.org/maintenancescripts.git


More information about the x2go-commits mailing list