diff libervia/backend/plugins/plugin_merge_req_mercurial.py @ 4270:0d7bb4df2343

Reformatted code base using black.
author Goffi <goffi@goffi.org>
date Wed, 19 Jun 2024 18:44:57 +0200
parents 4b842c1fb686
children
line wrap: on
line diff
--- a/libervia/backend/plugins/plugin_merge_req_mercurial.py	Tue Jun 18 12:06:45 2024 +0200
+++ b/libervia/backend/plugins/plugin_merge_req_mercurial.py	Wed Jun 19 18:44:57 2024 +0200
@@ -24,6 +24,7 @@
 from libervia.backend.core.constants import Const as C
 from libervia.backend.core import exceptions
 from libervia.backend.core.log import getLogger
+
 log = getLogger(__name__)
 
 
@@ -34,15 +35,16 @@
     C.PI_DEPENDENCIES: ["MERGE_REQUESTS"],
     C.PI_MAIN: "MercurialHandler",
     C.PI_HANDLER: "no",
-    C.PI_DESCRIPTION: _("""Merge request handler for Mercurial""")
+    C.PI_DESCRIPTION: _("""Merge request handler for Mercurial"""),
 }
 
 SHORT_DESC = D_("handle Mercurial repository")
-CLEAN_RE = re.compile(r'[^\w -._]', flags=re.UNICODE)
+CLEAN_RE = re.compile(r"[^\w -._]", flags=re.UNICODE)
 
 
 class MercurialProtocol(async_process.CommandProtocol):
     """handle hg commands"""
+
     name = "Mercurial"
     command = None
 
@@ -65,45 +67,58 @@
 
 
 class MercurialHandler(object):
-    data_types = ('mercurial_changeset',)
+    data_types = ("mercurial_changeset",)
 
     def __init__(self, host):
         log.info(_("Mercurial merge request handler initialization"))
         try:
-            MercurialProtocol.command = which('hg')[0]
+            MercurialProtocol.command = which("hg")[0]
         except IndexError:
-            raise exceptions.NotFound(_("Mercurial executable (hg) not found, "
-                                        "can't use Mercurial handler"))
+            raise exceptions.NotFound(
+                _("Mercurial executable (hg) not found, " "can't use Mercurial handler")
+            )
         self.host = host
-        self._m = host.plugins['MERGE_REQUESTS']
-        self._m.register('mercurial', self, self.data_types, SHORT_DESC)
-
+        self._m = host.plugins["MERGE_REQUESTS"]
+        self._m.register("mercurial", self, self.data_types, SHORT_DESC)
 
     def check(self, repository):
-        d = MercurialProtocol.run(repository, 'identify')
+        d = MercurialProtocol.run(repository, "identify")
         d.addCallback(lambda __: True)
         d.addErrback(lambda __: False)
         return d
 
     def export(self, repository):
         d = MercurialProtocol.run(
-            repository, 'export', '-g', '-r', 'outgoing() and ancestors(.)',
-            '--encoding=utf-8'
+            repository,
+            "export",
+            "-g",
+            "-r",
+            "outgoing() and ancestors(.)",
+            "--encoding=utf-8",
         )
-        d.addCallback(lambda data: data.decode('utf-8'))
+        d.addCallback(lambda data: data.decode("utf-8"))
         return d
 
     def import_(self, repository, data, data_type, item_id, service, node, extra):
         parsed_data = self.parse(data)
         try:
-            parsed_name = parsed_data[0]['commit_msg'].split('\n')[0]
-            parsed_name = CLEAN_RE.sub('', parsed_name)[:40]
+            parsed_name = parsed_data[0]["commit_msg"].split("\n")[0]
+            parsed_name = CLEAN_RE.sub("", parsed_name)[:40]
         except Exception:
-            parsed_name = ''
-        name = 'mr_{item_id}_{parsed_name}'.format(item_id=CLEAN_RE.sub('', item_id),
-                                                   parsed_name=parsed_name)
-        return MercurialProtocol.run(repository, 'qimport', '-g', '--name', name,
-                                     '--encoding=utf-8', '-', stdin=data)
+            parsed_name = ""
+        name = "mr_{item_id}_{parsed_name}".format(
+            item_id=CLEAN_RE.sub("", item_id), parsed_name=parsed_name
+        )
+        return MercurialProtocol.run(
+            repository,
+            "qimport",
+            "-g",
+            "--name",
+            name,
+            "--encoding=utf-8",
+            "-",
+            stdin=data,
+        )
 
     def parse(self, data, data_type=None):
         lines = data.splitlines()
@@ -113,55 +128,62 @@
             patch = {}
             commit_msg = []
             diff = []
-            state = 'init'
-            if lines[0] != '# HG changeset patch':
-                raise exceptions.DataError(_('invalid changeset signature'))
+            state = "init"
+            if lines[0] != "# HG changeset patch":
+                raise exceptions.DataError(_("invalid changeset signature"))
             # line index of this patch in the whole data
             patch_idx = total_lines - len(lines)
             del lines[0]
 
             for idx, line in enumerate(lines):
-                if state == 'init':
-                    if line.startswith('# '):
-                        if line.startswith('# User '):
+                if state == "init":
+                    if line.startswith("# "):
+                        if line.startswith("# User "):
                             elems = line[7:].split()
                             if not elems:
                                 continue
                             last = elems[-1]
-                            if (last.startswith('<') and last.endswith('>')
-                                and '@' in last):
+                            if (
+                                last.startswith("<")
+                                and last.endswith(">")
+                                and "@" in last
+                            ):
                                 patch[self._m.META_EMAIL] = elems.pop()[1:-1]
-                            patch[self._m.META_AUTHOR] = ' '.join(elems)
-                        elif line.startswith('# Date '):
+                            patch[self._m.META_AUTHOR] = " ".join(elems)
+                        elif line.startswith("# Date "):
                             time_data = line[7:].split()
                             if len(time_data) != 2:
-                                log.warning(_('unexpected time data: {data}')
-                                            .format(data=line[7:]))
+                                log.warning(
+                                    _("unexpected time data: {data}").format(
+                                        data=line[7:]
+                                    )
+                                )
                                 continue
-                            patch[self._m.META_TIMESTAMP] = (int(time_data[0])
-                                                             + int(time_data[1]))
-                        elif line.startswith('# Node ID '):
+                            patch[self._m.META_TIMESTAMP] = int(time_data[0]) + int(
+                                time_data[1]
+                            )
+                        elif line.startswith("# Node ID "):
                             patch[self._m.META_HASH] = line[10:]
-                        elif line.startswith('# Parent  '):
+                        elif line.startswith("# Parent  "):
                             patch[self._m.META_PARENT_HASH] = line[10:]
                     else:
-                        state = 'commit_msg'
-                if state == 'commit_msg':
-                    if line.startswith('diff --git a/'):
-                        state = 'diff'
+                        state = "commit_msg"
+                if state == "commit_msg":
+                    if line.startswith("diff --git a/"):
+                        state = "diff"
                         patch[self._m.META_DIFF_IDX] = patch_idx + idx + 1
                     else:
                         commit_msg.append(line)
-                if state == 'diff':
-                    if line.startswith('# ') or idx == len(lines)-1:
+                if state == "diff":
+                    if line.startswith("# ") or idx == len(lines) - 1:
                         # a new patch is starting or we have reached end of patches
-                        if idx == len(lines)-1:
+                        if idx == len(lines) - 1:
                             # end of patches, we need to keep the line
                             diff.append(line)
-                        patch[self._m.META_COMMIT_MSG] = '\n'.join(commit_msg)
-                        patch[self._m.META_DIFF] = '\n'.join(diff)
+                        patch[self._m.META_COMMIT_MSG] = "\n".join(commit_msg)
+                        patch[self._m.META_DIFF] = "\n".join(diff)
                         patches.append(patch)
-                        if idx == len(lines)-1:
+                        if idx == len(lines) - 1:
                             del lines[:]
                         else:
                             del lines[:idx]