diff sat_frontends/jp/cmd_blog.py @ 3568:04283582966f

core, frontends: fix invalid translatable strings. Some f-strings where used in translatable text, this has been fixed by using explicit `format()` call (using a script based on `tokenize`). As tokenize messes with spaces, a reformating tool (`black`) has been applied to some files afterwards.
author Goffi <goffi@goffi.org>
date Mon, 14 Jun 2021 18:35:12 +0200
parents 62f490eff51c
children 5f65f4e9f8cb 82e616b70a2a
line wrap: on
line diff
--- a/sat_frontends/jp/cmd_blog.py	Mon Jun 14 12:19:21 2021 +0200
+++ b/sat_frontends/jp/cmd_blog.py	Mon Jun 14 18:35:12 2021 +0200
@@ -100,7 +100,7 @@
             if k and ext == v:
                 return k
 
-    # if not found, we use current syntax
+                # if not found, we use current syntax
     return await host.bridge.getParamA("Syntax", "Composition", "value", host.profile)
 
 
@@ -125,15 +125,17 @@
                 self.current_syntax = self.args.syntax = syntax
             except Exception as e:
                 if e.classname == "NotFound":
-                    self.parser.error(_(f"unknown syntax requested ({self.args.syntax})"))
+                    self.parser.error(
+                        _("unknown syntax requested ({syntax})").format(
+                            syntax=self.args.syntax
+                        )
+                    )
                 else:
                     raise e
         return self.args.syntax
 
     def add_parser_options(self):
-        self.parser.add_argument(
-            "-T", "--title", help=_("title of the item")
-        )
+        self.parser.add_argument("-T", "--title", help=_("title of the item"))
         self.parser.add_argument(
             "-t",
             "--tag",
@@ -148,13 +150,22 @@
 
         comments_group = self.parser.add_mutually_exclusive_group()
         comments_group.add_argument(
-            "-C", "--comments", action="store_const", const=True, dest="comments",
-            help=_("enable comments (default: comments not enabled except if they "
-                   "already exist)")
+            "-C",
+            "--comments",
+            action="store_const",
+            const=True,
+            dest="comments",
+            help=_(
+                "enable comments (default: comments not enabled except if they "
+                "already exist)"
+            ),
         )
         comments_group.add_argument(
-            "--no-comments", action="store_const", const=False, dest="comments",
-            help=_("disable comments (will remove comments node if it exist)")
+            "--no-comments",
+            action="store_const",
+            const=False,
+            dest="comments",
+            help=_("disable comments (will remove comments node if it exist)"),
         )
 
         self.parser.add_argument(
@@ -182,7 +193,7 @@
         if self.args.comments is not None:
             mb_data["allow_comments"] = self.args.comments
         if self.args.tag:
-            mb_data['tags'] = self.args.tag
+            mb_data["tags"] = self.args.tag
         if self.args.title is not None:
             mb_data["title"] = self.args.title
         if self.args.language is not None:
@@ -222,9 +233,7 @@
                 self.profile,
             )
         except Exception as e:
-            self.disp(
-                f"can't send item: {e}", error=True
-            )
+            self.disp(f"can't send item: {e}", error=True)
             self.host.quit(C.EXIT_BRIDGE_ERRBACK)
         else:
             self.disp("Item published")
@@ -261,12 +270,12 @@
 
     def template_data_mapping(self, data):
         items, blog_items = data
-        blog_items['items'] = items
+        blog_items["items"] = items
         return {"blog_items": blog_items}
 
     def format_comments(self, item, keys):
         lines = []
-        for data in item.get('comments', []):
+        for data in item.get("comments", []):
             lines.append(data["uri"])
             for k in ("node", "service"):
                 if OUTPUT_OPT_NO_HEADER in self.args.output_opts:
@@ -277,7 +286,7 @@
         return "\n".join(lines)
 
     def format_tags(self, item, keys):
-        tags = item.pop('tags', [])
+        tags = item.pop("tags", [])
         return ", ".join(tags)
 
     def format_updated(self, item, keys):
@@ -359,7 +368,7 @@
                 if isinstance(value, bool):
                     value = str(value).lower()
                 self.disp(header + value)
-            # we want a separation line after each item but the last one
+                # we want a separation line after each item but the last one
             if idx < len(items) - 1:
                 print("")
 
@@ -393,7 +402,7 @@
             else:
                 author = published = updated = None
             if verbosity > 1:
-                tags = item.pop('tags', [])
+                tags = item.pop("tags", [])
             else:
                 tags = None
             content = item.get("content")
@@ -428,14 +437,14 @@
                     self.args.max,
                     self.args.items,
                     self.getPubsubExtra(),
-                    self.profile
+                    self.profile,
                 )
             )
         except Exception as e:
             self.disp(f"can't get blog items: {e}", error=True)
             self.host.quit(C.EXIT_BRIDGE_ERRBACK)
         else:
-            items = mb_data.pop('items')
+            items = mb_data.pop("items")
             await self.output((items, mb_data))
             self.host.quit(C.EXIT_OK)
 
@@ -483,7 +492,8 @@
         # we first construct metadata from edited item ones and CLI argumments
         # or re-use the existing one if it exists
         meta_file_path = content_file_path.with_name(
-            content_file_path.stem + common.METADATA_SUFF)
+            content_file_path.stem + common.METADATA_SUFF
+        )
         if meta_file_path.exists():
             self.disp("Metadata file already exists, we re-use it")
             try:
@@ -499,20 +509,20 @@
         else:
             mb_data = {} if mb_data is None else mb_data.copy()
 
-        # in all cases, we want to remove unwanted keys
+            # in all cases, we want to remove unwanted keys
         for key in KEY_TO_REMOVE_METADATA:
             try:
                 del mb_data[key]
             except KeyError:
                 pass
-        # and override metadata with command-line arguments
+                # and override metadata with command-line arguments
         self.setMbDataFromArgs(mb_data)
 
         if self.args.no_publish:
             mb_data["publish"] = False
 
-        # then we create the file and write metadata there, as JSON dict
-        # XXX: if we port jp one day on Windows, O_BINARY may need to be added here
+            # then we create the file and write metadata there, as JSON dict
+            # XXX: if we port jp one day on Windows, O_BINARY may need to be added here
         with os.fdopen(
             os.open(meta_file_path, os.O_RDWR | os.O_CREAT | os.O_TRUNC, 0o600), "w+b"
         ) as f:
@@ -556,7 +566,7 @@
                 )
             )
 
-        # we launch editor
+            # we launch editor
         coroutines.append(
             self.runEditor(
                 "blog_editor_args",
@@ -590,11 +600,9 @@
         items = [item] if item else []
 
         mb_data = data_format.deserialise(
-            await self.host.bridge.mbGet(
-                service, node, 1, items, {}, self.profile
-            )
+            await self.host.bridge.mbGet(service, node, 1, items, {}, self.profile)
         )
-        item = mb_data['items'][0]
+        item = mb_data["items"][0]
 
         try:
             content = item["content_xhtml"]
@@ -612,8 +620,8 @@
 
         if content and self.current_syntax == SYNTAX_XHTML:
             content = content.strip()
-            if not content.startswith('<div>'):
-                content = '<div>' + content + '</div>'
+            if not content.startswith("<div>"):
+                content = "<div>" + content + "</div>"
             try:
                 from lxml import etree
             except ImportError:
@@ -630,15 +638,20 @@
         SYNTAX_EXT.update(config.getConfig(self.sat_conf, "jp", CONF_SYNTAX_EXT, {}))
         self.current_syntax = await self.get_current_syntax()
 
-        (self.pubsub_service, self.pubsub_node, self.pubsub_item, content_file_path,
-         content_file_obj, mb_data,) = await self.getItemPath()
+        (
+            self.pubsub_service,
+            self.pubsub_node,
+            self.pubsub_item,
+            content_file_path,
+            content_file_obj,
+            mb_data,
+        ) = await self.getItemPath()
 
         await self.edit(content_file_path, content_file_obj, mb_data=mb_data)
         self.host.quit()
 
 
 class Rename(base.CommandBase):
-
     def __init__(self, host):
         base.CommandBase.__init__(
             self,
@@ -650,10 +663,7 @@
         )
 
     def add_parser_options(self):
-        self.parser.add_argument(
-            "new_id",
-            help=_("new item id to use")
-        )
+        self.parser.add_argument("new_id", help=_("new item id to use"))
 
     async def start(self):
         try:
@@ -665,14 +675,13 @@
                 self.profile,
             )
         except Exception as e:
-            self.disp(
-                f"can't rename item: {e}", error=True
-            )
+            self.disp(f"can't rename item: {e}", error=True)
             self.host.quit(C.EXIT_BRIDGE_ERRBACK)
         else:
             self.disp("Item renamed")
             self.host.quit(C.EXIT_OK)
 
+
 class Preview(base.CommandBase, common.BaseEdit):
     # TODO: need to be rewritten with template output
 
@@ -735,9 +744,9 @@
         xhtml = (
             f'<html xmlns="http://www.w3.org/1999/xhtml">'
             f'<head><meta http-equiv="Content-Type" content="text/html;charset=utf-8" />'
-            f'</head>'
-            f'<body>{content}</body>'
-            f'</html>'
+            f"</head>"
+            f"<body>{content}</body>"
+            f"</html>"
         )
 
         with open(self.preview_file_path, "wb") as f:
@@ -791,18 +800,19 @@
         else:
             update_cb = self.updatePreviewExt
 
-        # which file do we need to edit?
+            # which file do we need to edit?
         if self.args.file == "current":
             self.content_file_path = self.getCurrentFile(self.profile)
         else:
             try:
                 self.content_file_path = Path(self.args.file).resolve(strict=True)
             except FileNotFoundError:
-                self.disp(_(f'File "{self.args.file}" doesn\'t exist!'))
+                self.disp(_('File "{file}" doesn\'t exist!').format(file=self.args.file))
                 self.host.quit(C.EXIT_NOT_FOUND)
 
         self.syntax = await guessSyntaxFromPath(
-            self.host, sat_conf, self.content_file_path)
+            self.host, sat_conf, self.content_file_path
+        )
 
         # at this point the syntax is converted, we can display the preview
         preview_file = tempfile.NamedTemporaryFile(suffix=".xhtml", delete=False)
@@ -825,10 +835,10 @@
             watcher_kwargs = {
                 # Watcher don't accept Path so we convert to string
                 "path": str(self.content_file_path),
-                "alias": 'content_file',
+                "alias": "content_file",
                 "flags": aionotify.Flags.CLOSE_WRITE
-                         | aionotify.Flags.DELETE_SELF
-                         | aionotify.Flags.MOVE_SELF,
+                | aionotify.Flags.DELETE_SELF
+                | aionotify.Flags.MOVE_SELF,
             }
             watcher.watch(**watcher_kwargs)
 
@@ -839,14 +849,15 @@
                 while True:
                     event = await watcher.get_event()
                     self.disp("Content updated", 1)
-                    if event.flags & (aionotify.Flags.DELETE_SELF
-                                      | aionotify.Flags.MOVE_SELF):
+                    if event.flags & (
+                        aionotify.Flags.DELETE_SELF | aionotify.Flags.MOVE_SELF
+                    ):
                         self.disp(
                             "DELETE/MOVE event catched, changing the watch",
                             2,
                         )
                         try:
-                            watcher.unwatch('content_file')
+                            watcher.unwatch("content_file")
                         except IOError as e:
                             self.disp(
                                 f"Can't remove the watch: {e}",
@@ -869,7 +880,7 @@
             finally:
                 os.unlink(self.preview_file_path)
                 try:
-                    watcher.unwatch('content_file')
+                    watcher.unwatch("content_file")
                 except IOError as e:
                     self.disp(
                         f"Can't remove the watch: {e}",
@@ -893,9 +904,7 @@
             nargs="?",
             help=_("importer name, nothing to display importers list"),
         )
-        self.parser.add_argument(
-            "--host", help=_("original blog host")
-        )
+        self.parser.add_argument("--host", help=_("original blog host"))
         self.parser.add_argument(
             "--no-images-upload",
             action="store_true",
@@ -954,13 +963,16 @@
             )
             self.disp(
                 _(
-                    f"\nTo redirect old URLs to new ones, put the following lines in your"
-                    f" sat.conf file, in [libervia] section:\n\n{conf}"
-                )
+                    "\nTo redirect old URLs to new ones, put the following lines in your"
+                    " sat.conf file, in [libervia] section:\n\n{conf}"
+                ).format(conf=conf)
             )
 
     async def onProgressError(self, error_msg):
-        self.disp(_(f"Error while uploading blog: {error_msg}"), error=True)
+        self.disp(
+            _("Error while uploading blog: {error_msg}").format(error_msg=error_msg),
+            error=True,
+        )
 
     async def start(self):
         if self.args.location is None:
@@ -968,8 +980,8 @@
                 if getattr(self.args, name):
                     self.parser.error(
                         _(
-                            f"{name} argument can't be used without location argument"
-                        )
+                            "{name} argument can't be used without location argument"
+                        ).format(name=name)
                     )
             if self.args.importer is None:
                 self.disp(
@@ -1022,13 +1034,14 @@
                 )
             except Exception as e:
                 self.disp(
-                    _(f"Error while trying to import a blog: {e}"),
+                    _("Error while trying to import a blog: {e}").format(e=e),
                     error=True,
                 )
                 self.host.quit(1)
 
             await self.set_progress_id(progress_id)
 
+
 class Blog(base.CommandBase):
     subcommands = (Set, Get, Edit, Rename, Preview, Import)