changeset 4919f1643360 in tryton-tools:default
details: https://hg.tryton.org/tryton-tools?cmd=changeset;node=4919f1643360
description:
        Add Python3 support to mercurial hooks
diffstat:

 hgbranch.py   |   4 +-
 hgrietveld.py |  68 +++++++++++++++++++++++--------------------
 hgroundup.py  |  92 +++++++++++++++++++++++++++++++---------------------------
 3 files changed, 87 insertions(+), 77 deletions(-)

diffs (304 lines):

diff -r 50a4668f37de -r 4919f1643360 hgbranch.py
--- a/hgbranch.py       Sun Sep 27 12:18:21 2020 +0200
+++ b/hgbranch.py       Sun Sep 27 12:19:39 2020 +0200
@@ -16,6 +16,6 @@
         ctx = repo[rev]
         branch = ctx.branch()
         if not BRANCH_PATTERN.match(branch):
-            raise error.Abort('invalid branch name "%s".' % branch)
+            raise error.Abort(b'invalid branch name "%s".' % branch)
         else:
-            ui.debug('valid branch name "%s".' % branch)
+            ui.debug(b'valid branch name "%s".' % branch)
diff -r 50a4668f37de -r 4919f1643360 hgrietveld.py
--- a/hgrietveld.py     Sun Sep 27 12:18:21 2020 +0200
+++ b/hgrietveld.py     Sun Sep 27 12:19:39 2020 +0200
@@ -27,19 +27,18 @@
 import posixpath
 import traceback
 
-from string import Template
 from email.mime.text import MIMEText
 
 from mercurial.templatefilters import person
-from mercurial.encoding import fromlocal
+from mercurial.encoding import fromlocal, unifromlocal, unitolocal
 from mercurial import util
 
 ISSUE_PATTERN = re.compile(
-    r'(?:\breview|\bcodereview)\s*(?P<issue_id>[0-9]{4,})', re.I)
-COMMENT_TEMPLATE = """\
-New changeset ${changeset_id} by $author in branch '${branch}':
-${commit_msg}
-${changeset_url}
+    rb'(?:\breview|\bcodereview)\s*(?P<issue_id>[0-9]{4,})', re.I)
+COMMENT_TEMPLATE = b"""\
+New changeset %(changeset_id)s by %(author)s in branch '%(branch)s':
+%(commit_msg)s
+%(changeset_url)s
 """
 
 
@@ -58,7 +57,7 @@
     if count < 0:
         return
     while count > 0:
-        c = path.find('/')
+        c = path.find(b'/')
         if c == -1:
             break
         path = path[c + 1:]
@@ -71,17 +70,17 @@
 
     Return True if updating the Rietveld issue fails, else False.
     """
-    root = strip(repo.root, int(ui.config('hgrietveld', 'strip', -1)))
-    repourl = (ui.config('hgrietveld', 'baseurl')
-        or ui.config('web', 'baseurl') or '')
+    root = strip(repo.root, int(ui.config(b'hgrietveld', b'strip', -1)))
+    repourl = (ui.config(b'hgrietveld', b'baseurl')
+        or ui.config(b'web', b'baseurl') or b'')
     if repourl:
         repourl += root
-    repourl = posixpath.join(repourl, 'rev/')
-    fromaddr = ui.config('hgrietveld', 'fromaddr')
-    toaddr = ui.config('hgrietveld', 'toaddr')
-    mailrelay = ui.config('hgrietveld', 'mailrelay', default='')
+    repourl = posixpath.join(repourl, b'rev/')
+    fromaddr = ui.config(b'hgrietveld', b'fromaddr')
+    toaddr = ui.config(b'hgrietveld', b'toaddr')
+    mailrelay = ui.config(b'hgrietveld', b'mailrelay', default=b'')
     if not mailrelay:
-        mailrelay = ui.config('smtp', 'host', default='')
+        mailrelay = ui.config(b'smtp', b'host', default=b'')
     for var in ('repourl', 'fromaddr', 'toaddr'):
         if not locals()[var]:
             raise RuntimeError(
@@ -99,30 +98,34 @@
         ids = set()
         for match in matches:
             data = match.groupdict()
-            ui.debug('match in commit msg: %s\n' % data)
+            ui.debug(b'match in commit msg: %s\n' % data['issue_id'])
             # check for duplicated issue numbers in the same commit msg
             if data['issue_id'] in ids:
                 continue
             ids.add(data['issue_id'])
-            comment = Template(COMMENT_TEMPLATE).substitute({
-                'author': fromlocal(person(ctx.user())),
-                'branch': ctx.branch(),
-                'changeset_id': str(ctx),
-                'changeset_url': posixpath.join(repourl, str(ctx)),
-                'commit_msg': description.splitlines()[0],
-            })
+            comment = COMMENT_TEMPLATE % {
+                b'author': fromlocal(person(ctx.user())),
+                b'branch': bytes(ctx.branch()),
+                b'changeset_id': bytes(ctx),
+                b'changeset_url': posixpath.join(repourl, bytes(ctx)),
+                b'commit_msg': description.splitlines()[0],
+                }
             add_comment(issues, data, comment)
     if issues:
         try:
-            send_comments(mailrelay, fromaddr, toaddr, issues)
-            ui.status("sent email to rietveld at " + toaddr + '\n')
+            send_comments(
+                unifromlocal(mailrelay),
+                unifromlocal(fromaddr),
+                unifromlocal(toaddr),
+                issues)
+            ui.status(b"sent email to rietveld at " + toaddr + b'\n')
         except Exception as err:
             # make sure an issue updating rietveld does not prevent an
             # otherwise successful push.
-            ui.warn("sending email to rietveld at %s failed: %s\n" %
-                    (toaddr, err))
+            ui.warn(b"sending email to rietveld at %s failed: %s\n" %
+                    (toaddr, unitolocal(str(err))))
     else:
-        ui.debug("no issues to send to rietveld\n")
+        ui.debug(b"no issues to send to rietveld\n")
     return False
 
 
@@ -140,11 +143,12 @@
     s = smtplib.SMTP(mailrelay)
     try:
         for issue_id, data in issues.iteritems():
-            msg = MIMEText('\n\n'.join(data['comments']),
-                           _subtype='plain', _charset='utf8')
+            msg = MIMEText(
+                unifromlocal(b'\n\n'.join(data['comments'])),
+                _subtype='plain', _charset='utf8')
             msg['From'] = fromaddr
             msg['To'] = toaddr
-            msg['Subject'] = "(issue%s)" % issue_id
+            msg['Subject'] = unifromlocal(b"(issue%s)" % issue_id)
             s.sendmail(fromaddr, toaddr, msg.as_string())
     finally:
         s.quit()
diff -r 50a4668f37de -r 4919f1643360 hgroundup.py
--- a/hgroundup.py      Sun Sep 27 12:18:21 2020 +0200
+++ b/hgroundup.py      Sun Sep 27 12:19:39 2020 +0200
@@ -33,19 +33,18 @@
 import posixpath
 import traceback
 
-from string import Template
 from email.mime.text import MIMEText
 
 from mercurial.templatefilters import person
-from mercurial.encoding import fromlocal
+from mercurial.encoding import fromlocal, unifromlocal, unitolocal
 from mercurial import util
 
-ISSUE_PATTERN = re.compile(r'(?:#|\bissue|\bbug)\s*(?P<issue_id>[0-9]{1,})',
+ISSUE_PATTERN = re.compile(rb'(?:#|\bissue|\bbug)\s*(?P<issue_id>[0-9]{1,})',
                            re.I)
-COMMENT_TEMPLATE = """\
-New changeset ${changeset_id} by $author in branch '${branch}':
-${commit_msg}
-${changeset_url}
+COMMENT_TEMPLATE = b"""\
+New changeset %(changeset_id)s by %(author)s in branch '%(branch)s':
+%(commit_msg)s
+%(changeset_url)s
 """
 
 
@@ -64,7 +63,7 @@
     if count < 0:
         return
     while count > 0:
-        c = path.find('/')
+        c = path.find(b'/')
         if c == -1:
             break
         path = path[c + 1:]
@@ -77,19 +76,19 @@
 
     Return True if updating the Roundup issue fails, else False.
     """
-    root = strip(repo.root, int(ui.config('hgroundup', 'strip', -1)))
-    repourl = (ui.config('hgroundup', 'baseurl')
-        or ui.config('web', 'baseurl') or '')
+    root = strip(repo.root, int(ui.config(b'hgroundup', b'strip', -1)))
+    repourl = (ui.config(b'hgroundup', b'baseurl')
+        or ui.config(b'web', b'baseurl') or b'')
     if repourl:
         repourl += root
-    repourl = posixpath.join(repourl, 'rev/')
-    fromaddr = ui.config('hgroundup', 'fromaddr')
-    toaddr = ui.config('hgroundup', 'toaddr')
-    mailrelay = ui.config('hgroundup', 'mailrelay', default='')
-    classname = ui.config('hgroundup', 'classname', default='issue')
-    status = ui.config('hgroundup', 'status', default='resolved')
+    repourl = posixpath.join(repourl, b'rev/')
+    fromaddr = ui.config(b'hgroundup', b'fromaddr')
+    toaddr = ui.config(b'hgroundup', b'toaddr')
+    mailrelay = ui.config(b'hgroundup', b'mailrelay', default=b'')
+    classname = ui.config(b'hgroundup', b'classname', default=b'issue')
+    status = ui.config(b'hgroundup', b'status', default=b'resolved')
     if not mailrelay:
-        mailrelay = ui.config('smtp', 'host', default='')
+        mailrelay = ui.config(b'smtp', b'host', default=b'')
     for var in ('repourl', 'fromaddr', 'toaddr'):
         if not locals()[var]:
             raise RuntimeError(
@@ -107,37 +106,42 @@
         ids = set()
         for match in matches:
             data = match.groupdict()
-            ui.debug('match in commit msg: %s\n' % data)
+            ui.debug(b'match in commit msg: %s\n' % data['issue_id'])
             # check for duplicated issue numbers in the same commit msg
             if data['issue_id'] in ids:
                 continue
             ids.add(data['issue_id'])
-            comment = Template(COMMENT_TEMPLATE).substitute({
-                'author': fromlocal(person(ctx.user())),
-                'branch': ctx.branch(),
-                'changeset_id': str(ctx),
-                'changeset_url': posixpath.join(repourl, str(ctx)),
-                'commit_msg': description.splitlines()[0],
-            })
+            comment = COMMENT_TEMPLATE % {
+                b'author': fromlocal(person(ctx.user())),
+                b'branch': bytes(ctx.branch()),
+                b'changeset_id': bytes(ctx),
+                b'changeset_url': posixpath.join(repourl, bytes(ctx)),
+                b'commit_msg': description.splitlines()[0],
+                }
             keywords = []
-            if ctx.branch() != 'default':
-                keywords.append('-backport')
+            if ctx.branch() != b'default':
+                keywords.append(b'-backport')
             add_comment(issues, data, comment, status, keywords)
     if issues:
         try:
-            send_comments(mailrelay, fromaddr, toaddr, issues, classname)
-            ui.status("sent email to roundup at " + toaddr + '\n')
+            send_comments(
+                unifromlocal(mailrelay),
+                unifromlocal(fromaddr),
+                unifromlocal(toaddr),
+                issues, classname)
+            ui.status(b"sent email to roundup at " + toaddr + b'\n')
         except Exception as err:
             # make sure an issue updating roundup does not prevent an
             # otherwise successful push.
-            ui.warn("sending email to roundup at %s failed: %s\n" %
-                    (toaddr, err))
+            raise
+            ui.warn(b"sending email to roundup at %s failed: %s\n" %
+                    (toaddr, unitolocal(str(err))))
     else:
-        ui.debug("no issues to send to roundup\n")
+        ui.debug(b"no issues to send to roundup\n")
     return False
 
 
-def add_comment(issues, data, comment, status='resolved', keywords=None):
+def add_comment(issues, data, comment, status=b'resolved', keywords=None):
     """Process a comment made in a commit message."""
     key = data['issue_id']
     if key in issues:
@@ -153,25 +157,27 @@
 
 def _format_properties(value):
     if isinstance(value, (list, tuple, set)):
-        return ','.join(value)
+        return b','.join(value)
     return value
 
 
-def send_comments(mailrelay, fromaddr, toaddr, issues, classname='issue'):
+def send_comments(mailrelay, fromaddr, toaddr, issues, classname=b'issue'):
     """Update the Roundup issue with a comment and changeset link."""
     s = smtplib.SMTP(mailrelay)
     try:
-        for issue_id, data in issues.iteritems():
+        for issue_id, data in issues.items():
             props = ''
             if data['properties']:
-                props = ' [%s]' % ';'.join(
-                    '%s=%s' % (k, _format_properties(v))
-                    for k, v in data['properties'].iteritems())
-            msg = MIMEText('\n\n'.join(data['comments']),
-                           _subtype='plain', _charset='utf8')
+                props = b' [%s]' % b';'.join(
+                    b'%s=%s' % (unitolocal(k), _format_properties(v))
+                    for k, v in data['properties'].items())
+            msg = MIMEText(
+                unifromlocal(b'\n\n'.join(data['comments'])),
+                _subtype='plain', _charset='utf8')
             msg['From'] = fromaddr
             msg['To'] = toaddr
-            msg['Subject'] = "[%s%s]%s" % (classname, issue_id, props)
+            msg['Subject'] = unifromlocal(
+                b"[%s%s]%s" % (classname, issue_id, props))
             s.sendmail(fromaddr, toaddr, msg.as_string())
     finally:
         s.quit()

Reply via email to